Operators and control flow

Dart · Essentials · 8 min

These are the everyday building blocks, and Dart 3's switch expressions replace many if/else chains.

if / else if / else work as in C-like languages; the condition must be a bool — Dart has no truthiness. The conditional operator cond ? a : b picks a value.

Loops:

  • for (var i = 0; i < n; i++) — classic counter loop; each iteration gets a fresh i, so closures capture the right value.
  • for (final item in items) — iterate any Iterable.
  • while and do { } while.
  • break and continue, with labels for nested loops.

switch in Dart 3 matches patterns. Cases don't fall through when they have a body, so no break is needed. Empty cases share the next body.

A switch expression produces a value:

final label = switch (code) {
  200 => 'ok',
  404 => 'not found',
  >= 500 => 'server error',
  _ => 'other',
};

Each case is pattern => expression, separated by commas; _ is the wildcard. Switch expressions must be exhaustive, which the compiler checks.

Useful operators: ~/ (integer division), % (remainder), is and is! (type tests, which also promote), as (cast), and the cascade .. (call several members on the same object).

Example

String describe(int code) => switch (code) {
      200 || 201 => 'success',
      >= 400 && < 500 => 'client error',
      >= 500 => 'server error',
      _ => 'other',
    };

void main() {
  for (final c in [200, 404, 503, 302]) {
    print('$c ${describe(c)}');
  }
  // 200 success / 404 client error / 503 server error / 302 other

  var total = 0;
  for (var i = 1; i <= 10; i++) {
    if (i.isOdd) continue;
    total += i;
  }
  print(total);                     // 30

  final sb = StringBuffer()
    ..write('a')
    ..write('b');                   // cascade
  print(sb.toString().isEmpty ? 'empty' : sb);  // ab
}

Remember

  • Conditions must be real bools
  • Switch expressions pattern => value must be exhaustive
  • .. cascades call several members on one object

Watch out for

  • Writing case 1: case 2: with bodies in Dart 2 style and expecting fall-through.

Check yourself

  1. What is `switch (7) { > 5 => 'big', _ => 'small' }`?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: dart.dev/language/branches