Sub topic 6
Iterating with for-in, forEach, and Iterable
This chapter assumes you know Dart variables, functions, generics such as List<int>, and null safety. It focuses on reading collection values without changing how a collection stores them.
Dart collections commonly provide an Iterable. An Iterable is a sequence that you can visit one element at a time. A List, Set, and many collection operations produce an iterable view.
`for-in`: the clearest loop
Use for-in when you need several statements, conditions, or early control flow such as break and continue.
void main() {
final scores = <int>[72, 88, 91];
for (final score in scores) {
if (score < 80) {
continue;
}
print('Passing score: $score');
}
}The variable score receives each value in order. With a list, the order is its index order. With a set, the order depends on the set implementation.
For a map, iterate over entries when you need both the key and the value:
void main() {
final prices = <String, double>{
'tea': 2.50,
'cake': 4.25,
};
for (final entry in prices.entries) {
print('${entry.key}: \$${entry.value}');
}
}You can also iterate over prices.keys or prices.values.
`forEach`: a callback for each value
forEach calls a function once for every element. A short callback is useful when the action is simple.
void main() {
final names = <String>['Ada', 'Lin', 'Sam'];
names.forEach((name) {
print(name.toUpperCase());
});
}An arrow function makes a one-expression callback shorter:
names.forEach((name) => print('Hello, $name'));Unlike a normal for-in loop, forEach does not support break or continue. A return exits only the callback invocation, not the whole iteration. Prefer for-in when the loop needs branching or early termination.
The `Iterable` working model
Methods such as where and map return an Iterable. These results are usually lazy, which means Dart does not calculate every result immediately. It calculates values as you request them.
void main() {
final numbers = <int>[1, 2, 3, 4, 5];
final evenSquares = numbers
.where((number) => number.isEven)
.map((number) => number * number);
for (final value in evenSquares) {
print(value); // 4, then 16
}
}The where operation keeps matching values. The map operation converts each remaining value. Calling toList() materializes the iterable as a list:
final values = evenSquares.toList();A lazy iterable can reflect later changes to a mutable source collection. If you need a stable snapshot, create a list or set immediately.
Common iteration errors
- Use
entrieswhen a map loop needs both keys and values. - Do not assume every
Iterableis a list. An iterable may not support indexing such asitems[0]. - Remember that
maptransforms values but does not mutate the original collection. - Use
toList()when an API requires aListor when you want to evaluate a lazy pipeline now.
Exercise
Which construct should you choose when you must stop after finding the first negative number: forEach or for-in?
Show answer
Choose for-in, because it supports break.