Explain it simply
Explain it simply
Imagine a cashier at a supermarket. The basket in front of her is a list, and she does the same thing for every item: pick it up, scan it, put it in the bag. That is a for-in loop: "for each item in the basket, scan it". She does not need to know how many items there are; the loop ends when the basket is empty.
A while loop is a different situation: "keep restocking the shelf until it holds 50 boxes". Nobody knows how many trips that takes, so you check the condition before every trip. A do-while loop is like tasting soup: you taste once first, and only then decide whether to add salt and taste again. A for loop with a counter is for when the number of laps is known, as in "run three laps".
Problem → Why → Solution
The problem: the loop runs one time too many
You total three prices from a list. You write the loop with a counter and, to be safe, use <= instead of < in the condition. The program prints nothing and stops with an error instead of the total. Counting from zero, a list of three items has valid positions 0, 1 and 2, but a <= comparison against the length also lets the loop run with i equal to 3 and ask for an item that does not exist.
The first three passes work, which is what makes this bug slippery: your test data looks fine until the last pass. Off-by-one mistakes at loop boundaries are probably the most common loop bug in every language.
void main() {
final prices = [3000, 5000, 7000];
var total = 0;
for (var i = 0; i <= prices.length; i++) {
total += prices[i]; // RangeError when i == 3
}
print('Total: $total'); // never reached
}Why does it fail?
Lists are zero-based, so the last valid index is length - 1. A counted loop that should visit every element must therefore stop while i < length. If you do not need the position at all, use for (final price in prices) and the whole class of bug disappears, because Dart hands you only elements that exist.
Core concept: four loops and the keywords that steer them
Dart has four loop statements and each one answers a different question. A for loop with a counter, for (var i = 0; i < n; i++), is for when you need the index or the arithmetic of counting. A for-in loop, for (final item in items), visits every element of a List, a Set or any other Iterable and leaves no index to get wrong. A while loop checks its condition before every pass and fits cases where you do not know in advance how many passes you need. A do-while loop runs its body first and checks afterwards, so it always runs at least once.
One lap of a counted for loop
-----------------------------
for (var i = 0; i < 3; i++) { body }
init: i = 0
|
v
+--> i < 3 ? --no--> leave the loop
| | yes
| v
| run body (break leaves, continue jumps to the update)
| |
| v
+--- update: i++Inside any loop, break leaves the nearest loop immediately and continue skips the rest of the current pass and jumps to the next one; in a counted for loop the update step (i++) still runs after a continue. When loops are nested, break only leaves the inner loop. Put a label in front of the outer loop (search:) and write break search; to leave both at once, or continue search; to jump to the outer loop's next pass.
Every loop needs an answer to two questions: what moves it forward, and what makes it stop? For for-in the answer is built in, because the iterable runs out. For while and do-while you must change something the condition depends on inside the body, or the loop never ends. Two more details are worth knowing early. First, the body of a for-in loop must not add or remove elements of the collection being iterated; Dart throws a ConcurrentModificationError. Second, list.forEach((x) { ... }) is a method call with a callback, not a loop statement, which gives it different rules for break and return, covered below.
- Test the condition / fetch next item
- False or no items left: exit the loop
- True: run the body (break / continue)
- Update the counter, return to the test
Every loop must answer: what moves it forward, and what makes it stop?
General pattern
for (var i = start; i < end; i++) { body } // counted loop
for (final item in iterable) { body } // every element
while (condition) { body } // test first
do { body } while (condition); // body first
label:
for (...) {
for (...) {
if (done) break label; // leaves both loops
}
}Do not forget the semicolon at the end of do-while. A label sits directly in front of a loop and is used with break label; or continue label;. In a for-in loop it is good style to declare the loop variable final.
Example: all four loops and a labelled break in one program
This program totals a list of prices with for-in and reads them back with an indexed counted loop. Then a while loop counts three attempts, and a do-while whose condition is false from the start shows that it still runs once. Finally it searches a 3x3 grid for the number 5 and leaves both loops at once with a labelled break. Predict the row and column on the last line before you run it.
void main() {
final prices = [3000, 5000, 7000];
var total = 0;
for (final price in prices) {
total += price;
}
print('Total: $total');
for (var i = 0; i < prices.length; i++) {
print('item ${i + 1} costs ${prices[i]}');
}
var attempt = 0;
while (attempt < 3) {
attempt++;
print('attempt $attempt');
}
var retries = 10;
do {
print('do-while ran once with retries=$retries');
retries++;
} while (retries < 3);
final grid = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
];
search:
for (var r = 0; r < grid.length; r++) {
for (var c = 0; c < grid[r].length; c++) {
if (grid[r][c] == 5) {
print('found 5 at row $r, column $c');
break search;
}
}
}
}Code breakdown
- for-in
for (final price in prices) {Dart hands each element of prices to price in turn. There is no index, so an off-by-one mistake is impossible, and the total is 3000 + 5000 + 7000 = 15000.
- Counted for
for (var i = 0; i < prices.length; i++) {An index is needed to print the item number, so a counter loop is the right tool here. With i < prices.length, i takes only 0, 1 and 2, so there is no RangeError, and i + 1 gives a human-friendly number.
- while
while (attempt < 3) {The condition is tested before every pass. attempt++ changes the variable the condition depends on, so the loop ends after three passes; without that line it would run forever.
- do-while
} while (retries < 3);retries starts at 10, so the condition is false from the beginning, yet the body runs first and one message is printed. Note the semicolon that ends a do-while.
- Labelled break
break search;A plain break would stop only the inner loop and let the outer one carry on. break search; leaves both loops through the label, so the search stops at row 1, column 1 where 5 lives.
Total: 15000
item 1 costs 3000
item 2 costs 5000
item 3 costs 7000
attempt 1
attempt 2
attempt 3
do-while ran once with retries=10
found 5 at row 1, column 1Maps, indexes and the collection for
You do not loop over a Map directly; you loop over map.entries, map.keys or map.values. Each entry has a key and a value, and with a Dart 3 pattern, for (final MapEntry(:key, :value) in map.entries), you pull both out as variables in one go. When you also want the index, iterable.indexed yields (index, element) records, so for (final (i, name) in names.indexed) removes the need to manage i by hand. You can use for inside a list literal as well: [for (var n = 1; n <= 4; n++) n * n] gives [1, 4, 9, 16]. This is called a collection for and is the same idea as using if inside a list.
void main() {
final stock = {'apple': 3, 'pear': 0, 'fig': 7};
for (final entry in stock.entries) {
print('${entry.key}: ${entry.value}');
}
for (final MapEntry(:key, :value) in stock.entries) {
if (value == 0) continue;
print('in stock: $key');
}
for (final (i, name) in ['Su', 'Aye'].indexed) {
print('$i $name');
}
final squares = [for (var n = 1; n <= 4; n++) n * n];
print(squares);
}Why forEach cannot break, and closures in loops
forEach is not a loop statement; it is a method that takes a function as an argument. A return inside the callback leaves only that one callback call, and then forEach moves on to the next element, so return behaves like continue. A break is a compile error because the callback contains no loop: "A break statement can't be used outside of a loop or switch statement." forEach also does not await an async callback. When you need to stop early or to await, use for-in.
One more thing worth knowing is how closures behave. In a Dart for (var i = 0; ...) loop every pass gets its own i, so functions created inside the loop remember the value of their own pass. With a while loop and a variable declared outside, all passes share one variable, so every function sees its final value.
void main() {
[1, 2, 3, 4].forEach((x) {
if (x == 2) return; // leaves this callback only, like continue
print('forEach saw $x');
});
for (final x in [1, 2, 3, 4]) {
if (x == 3) break; // really stops the loop
print('for-in saw $x');
}
final fromFor = <int Function()>[];
for (var i = 0; i < 3; i++) {
fromFor.add(() => i);
}
print(fromFor.map((f) => f()).toList());
final fromWhile = <int Function()>[];
var j = 0;
while (j < 3) {
fromWhile.add(() => j);
j++;
}
print(fromWhile.map((f) => f()).toList());
}In real projects
Where this shows up in real projects
Real programs loop constantly. A shopping cart loops over its lines to add up the total, a validator loops over form fields and collects every error, and a pagination routine uses while (true) to fetch page after page and break when the server returns an empty page. Retry logic is a loop with a hard upper bound, such as at most three attempts, so a failing network cannot keep your app busy forever.
In Flutter you rarely write a loop for the screen itself; you use a collection for inside a list literal, like [for (final task in tasks) TaskTile(task)], or a builder that Flutter calls for you. On a server or in a command-line tool, loops read files line by line and process records one at a time. Asynchronous streams have their own form, await for, which waits for each event in turn. When a loop only filters or transforms data, iterable methods such as where and map often say the same thing in one line, but when you need break, continue or several steps per item, the for-in loop is the clearer choice.
Common mistakes
Common mistakes
1. Forgetting the update that ends a while loop
In var n = 0; while (n < 3) { print(n); } nothing ever increases n, so the loop prints forever, and Dart reports no error. Whenever you write a while, ask what changes the condition, or switch to for-in where possible.
2. Changing a list while iterating over it
for (final x in items) { if (x.isEven) items.remove(x); } throws a ConcurrentModificationError with the message "Concurrent modification during iteration", because the list's length changed underneath the iterator. Use items.removeWhere((x) => x.isEven), or loop over a copy with for (final x in items.toList()) while you change the original.
3. Expecting break to work inside forEach
Writing break inside the callback does not compile, and return only leaves that one callback while the iteration carries on. Code that must stop as soon as it finds something belongs in a for-in loop, or in a method such as firstWhere or any.
void main() {
final a = [1, 2, 3, 4];
a.removeWhere((x) => x.isEven);
print(a);
final b = [1, 2, 3, 4];
for (final x in b.toList()) {
if (x.isEven) b.remove(x);
}
print(b);
}Best practices
Best practices
- Prefer for-in when you do not need the index; it removes off-by-one mistakes by construction.
- Declare the loop variable final, as in for (final item in items), so it cannot be changed by accident in the body.
- Give every retry or polling loop a hard upper bound on the number of attempts.
- When a loop body grows long, extract it into a function so the loop itself stays easy to read.
Mini challenge
Mini challenge: a warehouse stock check
Check a warehouse's stock map with three kinds of loop: for-in to list what is in stock, while to restock, and labelled nested loops to find the first matching pair.
- Loop over stock.entries with for-in, skip items whose quantity is 0 with continue, print the rest as "name: quantity" and add up the total units
- Use a while loop to restock 'nuts' (starting at 0) in batches of 15 until it reaches 50 or more, counting the batches
- Use two labelled nested for loops over stock.keys / stock.values and stop both at the first pair of items whose quantities total 60 or more
void main() {
final stock = {'bolts': 40, 'nuts': 0, 'screws': 25, 'washers': 0, 'rivets': 12};
// TODO 1: for-in over stock.entries; skip empty items with continue,
// print "name: quantity" and add up the units
// TODO 2: while loop: restock 'nuts' (it starts at 0) in batches of 15
// until it reaches 50 or more, counting the batches
// TODO 3: labelled nested for loops over the keys and values:
// stop both loops at the first pair of items totalling 60 or more
}Expected: bolts: 40 screws: 25 rivets: 12 total units: 77 nuts: 60 after 4 batches bolts + screws = 65
Show hint
In part one, call continue; when entry.value == 0. In part three take names = stock.keys.toList() and qty = stock.values.toList() and start the inner loop at j = i + 1, so an item is never added to itself and no pair is counted twice. Give the outer loop a label such as pairs: and write break pairs;.
Show solution
void main() {
final stock = {'bolts': 40, 'nuts': 0, 'screws': 25, 'washers': 0, 'rivets': 12};
var totalUnits = 0;
for (final entry in stock.entries) {
if (entry.value == 0) {
continue;
}
print('${entry.key}: ${entry.value}');
totalUnits += entry.value;
}
print('total units: $totalUnits');
var nuts = stock['nuts'] ?? 0;
var batches = 0;
while (nuts < 50) {
nuts += 15;
batches++;
}
print('nuts: $nuts after $batches batches');
final names = stock.keys.toList();
final qty = stock.values.toList();
pairs:
for (var i = 0; i < names.length; i++) {
for (var j = i + 1; j < names.length; j++) {
if (qty[i] + qty[j] >= 60) {
print('${names[i]} + ${names[j]} = ${qty[i] + qty[j]}');
break pairs;
}
}
}
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Use for when you need the index, for-in for every element, while when the count is unknown and do-while when the body must run at least once.
- break leaves the nearest loop and continue skips the current pass; a label lets them control both loops of a nested pair.
- forEach is not a loop statement and cannot break; use for-in when you must stop early.
- i <= length, a while without an update and changing a list while iterating are the classic loop bugs.
Dart language overview — Dart