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 freshi, so closures capture the right value.for (final item in items)— iterate anyIterable.whileanddo { } while.breakandcontinue, 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 => valuemust 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.