Control Flow

7.1 if / else and Conditional Expressions

if (score >= 90) {
  print('A');
} else if (score >= 80) {
  print('B');
} else {
  print('C');
}
final label = score >= 50 ? 'pass' : 'fail';

if (json case {'name': String name, 'age': int age}) {   // if-case (Dart 3)
  print('$name is $age');
}

7.2 switch Statements and Expressions (Dart 3)

// switch statement: no implicit fallthrough, no `break` needed for non-empty cases
switch (command) {
  case 'start' || 'run':
    start();
  case 'stop':
    stop();
  case var other when other.startsWith('go '):
    go(other.substring(3));
  default:
    print('Unknown command');
}

// switch expression
final description = switch (statusCode) {
  200 => 'OK',
  301 || 302 => 'Redirect',
  >= 400 && < 500 => 'Client error',
  >= 500 => 'Server error',
  _ => 'Unknown',
};

7.3 Loops

for (var i = 0; i < 5; i++) { print(i); }
for (final fruit in ['apple', 'banana']) { print(fruit); }
for (final MapEntry(:key, :value) in {'a': 1}.entries) { print('$key=$value'); }   // pattern in for-in
[1, 2, 3].forEach(print);

var n = 3;
while (n > 0) { n--; }
do { n++; } while (n < 3);

outer:
for (var i = 0; i < 3; i++) {
  for (var j = 0; j < 3; j++) {
    if (j == 1) continue outer;
    if (i == 2) break outer;
    print('$i,$j');
  }
}

7.4 assert

assert(age >= 0, 'Age must be non-negative');   // checked in debug/test (dart run --enable-asserts), ignored in production