Sub topic 5
Control flow: conditions and loops
This chapter assumes you know what variables and the bool, int, and String types are (covered in the variables chapter), and that you have written if and for in another language. The focus here is on where Dart differs from that language and on the mistakes those differences cause.
Conditions must be real booleans
Dart has no "truthy" or "falsy" values. The condition in if, while, do, and the ternary operator must have type bool. Writing if (1) or if (name) is a compile-time error.
void main() {
final temperature = 28;
if (temperature > 30) {
print('hot');
} else if (temperature > 20) {
print('warm');
} else {
print('cool');
}
final label = temperature > 20 ? 'warm' : 'cool';
print(label);
}A nullable bool? is not a bool either. Compare it explicitly:
void main() {
bool? enabled;
if (enabled == true) {
print('on');
} else {
print('off or unknown');
}
}Combine conditions with &&, ||, and !. The first two short-circuit: the right side runs only if the left side has not already decided the result. That lets you guard a risky check with a safe one, such as list.isNotEmpty && list.first > 0.
Braces are optional for a single statement, but the Dart style guide recommends them everywhere except for a short if on one line.
Choosing between branches
Use the form that matches the shape of the decision.
| Situation | Best fit |
|---|---|
| Two outcomes, one value | Ternary `a ? b : c` |
| A value that may be null | `??` or `??=` |
| Several unrelated conditions | `if` / `else if` chain |
| One value compared with many constants | `switch` |
| Picking a value from many cases | `switch` expression |
Switch statements
A Dart switch statement does not fall through. Each non-empty case ends on its own, so you do not write break. A case with an empty body does share the body of the next case, which is how you group values.
enum Level { low, medium, high }
String describe(Level level) {
switch (level) {
case Level.low:
return 'quiet';
case Level.medium:
case Level.high:
return 'busy';
}
}
void main() {
print(describe(Level.low));
print(describe(Level.high));
}Because Level is an enum and every value is handled, the compiler knows the function always returns. If you later add Level.critical and forget a case, the compiler reports an error on this switch. This check is called exhaustiveness, and it applies to enums, bool, and sealed classes. For other types such as int or String, add a default clause.
Dart 3 case clauses accept patterns, not only constants. These forms are enough for most conditions:
String classify(int n) {
switch (n) {
case 0:
return 'zero';
case 1 || 2 || 3:
return 'small';
case > 3 && < 100:
return 'medium';
default:
return 'other';
}
}
void main() {
for (final n in [0, 2, 50, 500, -4]) {
print('$n is ${classify(n)}');
}
}1 || 2 || 3 matches any of the three values. > 3 && < 100 combines two relational checks. The records and patterns chapter covers the rest of the pattern syntax, including destructuring.
Switch expressions
A switch expression produces a value, so it can sit on the right of = or after return. It uses => instead of :, has no case keyword, and separates arms with commas.
void main() {
const n = 7;
final size = switch (n) {
< 10 => 'small',
< 100 => 'medium',
_ => 'large',
};
print(size);
}The _ arm is the wildcard and plays the role of default. Arms are tried from top to bottom, and the first match wins. A switch expression must be exhaustive, so it needs _ or a full set of enum values.
Loops
Dart has four loop forms. Pick by what you know in advance.
| Loop | Use when |
|---|---|
| `for (init; test; step)` | You need the index or a custom step |
| `for (final x in iterable)` | You only need each element |
| `while (test)` | The number of repeats is unknown, and zero repeats is possible |
| `do { } while (test)` | The body must run at least once |
void main() {
for (var i = 0; i < 3; i++) {
print('index $i');
}
final names = ['Ada', 'Linus', 'Grace'];
for (final name in names) {
print(name);
}
var n = 3;
while (n > 0) {
print('countdown $n');
n--;
}
var attempts = 0;
do {
attempts++;
} while (attempts < 3);
print('attempts: $attempts');
}Prefer for-in when you do not need the index. It cannot go out of range, and it works on any Iterable, which includes lists, sets, and map keys or values.
break, continue, and labels
break leaves the nearest enclosing loop. continue skips to the next iteration. To affect an outer loop, put a label before it and name it.
void main() {
outer:
for (var row = 1; row <= 3; row++) {
for (var col = 1; col <= 3; col++) {
if (col == 2) continue;
if (row == 3) break outer;
print('$row,$col');
}
}
}This prints 1,1, 1,3, 2,1, and 2,3. On row 3 the break outer ends both loops at once. Use labels sparingly. If you need one often, extract the loops into a function and use return.
Closures capture each iteration separately
In a C-style for loop, Dart gives each iteration its own copy of the loop variable. A closure created in the body therefore remembers that iteration's value. Some languages, including older JavaScript with var, behave differently, so this is worth knowing.
void main() {
final printers = <void Function()>[];
for (var i = 0; i < 3; i++) {
printers.add(() => print(i));
}
for (final p in printers) {
p();
}
}This prints 0, 1, 2, not 3 three times.
Common errors
- Changing a collection while looping over it. Removing or adding elements inside
for (final x in items)throws aConcurrentModificationErrorat runtime. Useitems.removeWhere((x) => x == 2), or loop over a copy made withitems.toList(). - Using
forEachwhen you needbreak. The callback passed toforEachis a function, sobreakandcontinuedo not apply, andreturnonly leaves that one call. It also does not wait forawait. Usefor-ininstead. - Forgetting
defaulton a non-enum switch statement. The compiler may then reject the function because a path can return nothing. - Off-by-one bounds.
i <= list.lengthreads one past the end and throws aRangeError. Usei < list.length. - Expecting
if (value)to work. Write the comparison you mean, such asvalue != nullorvalue.isNotEmpty.
Conditions and loops inside collection literals
if and for can appear inside a list, set, or map literal. This is often clearer than building the collection with a loop and add.
void main() {
final loggedIn = true;
final menu = [
'Home',
if (loggedIn) 'Profile' else 'Sign in',
for (final i in [1, 2]) 'Item $i',
];
print(menu);
}Flutter code uses this form heavily to include widgets conditionally, so it pays to be comfortable with it. The next chapters build on both loops and collections.
Exercise
What does the following code print, and why? void main() { for (var i = 0; i < 5; i++) { if (i == 1) continue; if (i == 3) break; print(i); } }
Show answer
It prints 0 and then 2. When i is 1, continue skips the print and goes to the next iteration. When i is 3, break ends the loop before printing, so 4 is never reached.
Exercise
Rewrite this function as a switch expression, and explain why the wildcard arm must come last. String grade(int score) { if (score >= 90) return 'A'; if (score >= 80) return 'B'; return 'C'; }
Show answer
String grade(int score) => switch (score) { >= 90 => 'A', >= 80 => 'B', => 'C', }; Arms are tested from top to bottom and the first match wins. The wildcard matches every value, so if it came first it would always win and the other arms would never run.