Dart Loops
Loops repeat a block of code. Dart offers the classic C-style for, the for-in loop over any Iterable, while, do-while, and the forEach method. break and continue (optionally with labels) control the flow inside them.
The classic for loop
void main() {
for (var i = 1; i <= 5; i++) {
print('$i squared is ${i * i}');
}
// counting down by twos
for (var i = 10; i > 0; i -= 2) {
print('T-minus $i');
}
}1 squared is 1
2 squared is 4
3 squared is 9
4 squared is 16
5 squared is 25
T-minus 10
T-minus 8
T-minus 6
T-minus 4
T-minus 2
Note: Each iteration of a Dart
forloop gets a fresh copy of the loop variable. Closures created inside the loop capture the value for that iteration — a classic JavaScript bug that Dart avoids.
void main() {
var callbacks = <void Function()>[];
for (var i = 0; i < 3; i++) {
callbacks.add(() => print('callback $i'));
}
for (final cb in callbacks) {
cb();
}
}callback 0
callback 1
callback 2
for-in
for (final x in iterable) walks any Iterable: lists, sets, map keys/values/entries, strings' runes, ranges you build yourself, and more.
void main() {
final fruits = ['mango', 'lychee', 'durian'];
for (final fruit in fruits) {
print(fruit.toUpperCase());
}
final prices = {'tea': 2.0, 'coffee': 3.5};
for (final MapEntry(:key, :value) in prices.entries) {
print('$key costs $value');
}
for (final (index, fruit) in fruits.indexed) {
print('$index: $fruit');
}
}MANGO
LYCHEE
DURIAN
tea costs 2.0
coffee costs 3.5
0: mango
1: lychee
2: durian
fruits.indexed (Dart 3) yields (index, element) records, and MapEntry(:key, :value) is a pattern that destructures each entry — no more entry.key noise.
while and do-while
Use while when you don't know in advance how many iterations you need. do-while checks the condition after the body, so it always runs at least once.
void main() {
// Collatz sequence: how many steps to reach 1?
var n = 6;
var steps = 0;
while (n != 1) {
n = n.isEven ? n ~/ 2 : 3 * n + 1;
steps++;
}
print('6 reaches 1 in $steps steps');
var attempts = 0;
do {
attempts++;
print('attempt $attempts');
} while (attempts < 0); // condition is false, but the body ran once
}6 reaches 1 in 8 steps
attempt 1
break, continue and labels
breakleaves the loop immediately.continueskips to the next iteration.- A label (
outer:) letsbreak/continuetarget an outer loop.
void main() {
for (var i = 1; i <= 10; i++) {
if (i % 3 == 0) continue; // skip multiples of 3
if (i > 7) break; // stop after 7
print(i);
}
final grid = [
[1, 4, 7],
[2, 9, 5],
[8, 3, 6],
];
outer:
for (var r = 0; r < grid.length; r++) {
for (var c = 0; c < grid[r].length; c++) {
if (grid[r][c] == 9) {
print('found 9 at row $r, col $c');
break outer;
}
}
}
}1
2
4
5
7
found 9 at row 1, col 1
forEach vs for-in
list.forEach((x) => ...) works, but the Dart style guide prefers for-in for statements: it supports break, continue, return from the enclosing function and await. Use forEach only when you already have a function to pass, e.g. names.forEach(print);.
| Loop | Best for |
|---|---|
for (init; cond; step) |
Index arithmetic, custom steps |
for (final x in items) |
Visiting every element |
while |
Unknown number of iterations |
do-while |
At least one iteration (e.g. retry/prompt loops) |
await for |
Consuming a Stream (see Streams) |
Test yourself
How many times does the body of do { } while (false); run?
- 0
- 1
- Infinitely
- It doesn't compile
What does break outer; do in a nested loop?
- Exits only the inner loop
- Exits the loop labelled
outer - Restarts the outer loop
- Throws an exception
What does for (final (i, x) in list.indexed) give you?
- Only the indexes
- Pairs of index and element
- A copy of the list
- A Map