Chapter 08

  制御構文と例外処理文

heyhey1028
heyhey1028
2023.02.19に更新

制御構文

Dart の制御構文は他の言語で用いられるものとあまり変わりません。if elseforwhiledo whileswitchといった多くのプログラミング言語で用いられている構文が使えます。

分岐処理

if else

第二条件はelse if(条件式)となります。

void main() {
  int x = 10;
  if (x > 5) {
    print("x is greater than 5");
  } else if (x < 5) {
    print("x is less than 5");
  } else {
    print("x is equal to 5");
  }
}

switch

switch文では複数のケースで同一の処理を行いたい場合は、下記のcase 3:case 4:の様に詰めて記述します。

void main() {
  var number = 3;
  switch (number) {
    case 1:
      print('One');
      break;
    case 2:
      print('Two');
      break;
    case 3:
    case 4: // 詰めて記載する
      print('Three or Four');
      break;
    default:
      print('Number not supported');
      break;
  }
}

三項演算子

if else条件を短縮して表現する三項演算子も使い所が多いので覚えておきましょう。

  • 条件 ? 条件に合致する場合の値 : 条件に合致しない場合の値
void main() {
  int number = 7;

  // 三項演算子
  // ex. 2で割り切れる時は'Even'を代入、割り切れない場合は'Odd'を代入
  String result = (number % 2 == 0) ? 'Even' : 'Odd';

  print(result); // "Odd"
}

繰り返し処理

for

void main() {
  for(int i=0; i<10; i++) {
    print(i);
  }
}

while

処理前に条件判定をする繰り返し処理に便利です

void main() {
  int num = 5;

  while (num > 0) {
    print(num);
    num--;
  }
}

do while

処理後に条件判定をする繰り返し処理に便利です

void main() {
  int i = 0;
  do {
    print(i);
    i++;
  } while (i < 5);
}

for in

Flutter 開発で比較的よく使うのがこちらの配列やマップを回すfor inです。

Map 型は.keysでキーのみを、.valuesでバリューのみを、.entriesで格納してるオブジェクトを取得する事ができます。

void main() {
  // List
  List<int> numbers = [1, 2, 3, 4, 5];
  for (int n in numbers) {
    print(n);
  }

  // Map
  Map<int,String> myMap = {81:'JP',1:'US',44:'GB'};

  // keyのみをループ処理
  for (int key in myMap.keys){
    print(key); // output: 81 1 44
  }

  // valueのみをループ処理
  for (var value in myMap.values) {
    print(value); // output: JP US GB
  }

  // keyとvalueどちらにもアクセスしたい場合
  for (var entry in myMap.entries) {
    print('Key: ${entry.key}, Value: ${entry.value}');
  }

  // output:
  // Key: 81, Value: JP
  // Key: 1, Value: US
  // Key: 44, Value: GB

}

continuebreak

条件分岐や繰り返し処理の挙動を変えるcontinuebreakもサポートされています。

繰り返し処理で使う

breakで繰り返し処理を中断、continueで後続処理を行わず、次のインデックスの処理に移ります。

void main() {
  for(int i=0; i<10; i++) {
    if(i == 4){
      break;
    }
    if(i == 7){
      continue;
    }
    print(i);
  }
}

条件分岐(switch) 文で使う

switch 文ではラベルを条件に付与する事もでき、continueを用いることでそのラベルが付与された処理に飛ばす事ができます。

下記ではcase 'B':条件の処理を実行したのち、cheerラベルが貼られたcase 'C':条件の処理も実行します。

breakは単純に switch 処理を終了させます。

void main() {
  var grade = 'B';

  switch (grade) {
    case 'A':
      print('Excellent work!');
      break;
    case 'B':
      print('Good job!');
      continue cheer; // ラベル名を指定
    cheer: // case 'C'にラベルを付与
    case 'C':
      print('You can do better!');
      break;
    default:
      print('Invalid grade!');
  }
}

例外処理文

try/catchfinallythrow

エラーハンドリングなどの例外処理を行う場合はtry/catchを用いてエラーをキャッチします。エラーをキャッチした後に実行したい処理があればfinally内に記述します。

任意にエラーを投げたい場合はthrowを使います。

またon データ型 catchとする事で特定のエラーのみキャッチする事が可能です。受け取るエラーオブジェクトの型に応じて処理を変えたい場合はon句を使ったcatchを併記する事も可能です

void main() {
  try {
    print("try block");
    throw Error();
  } catch(error,stackTrace) {
    print('error captured: $error')
  } finally {
    print("finally block");
  }

  // AppErrorとPlatformErrorで処理を分岐
  try {
    print("try block");
    throw Error();
  } on AppError catch(error,stackTrace) {
    print('App error captured: $error')
  } on PlatformError catch (error, stackTrace){
    print('Platform error captured: $error')
  } finally {
    print("finally block");
  }
}

まとめ

この章では制御構文や例外処理文について学びました。比較的特殊な構文はなく、javaScript にも似てシンプルなのでとっつきやすいかと思います。

次章では使うことも多い配列、マップ操作のメソッドについて学んでいきます。