Sub topic 6
Iterating with for-in, forEach, and Iterable
This chapter assumes you know basic Dart syntax, generics such as List<int>, and nullable types such as int?. You should also have met lists, maps, and sets. The chapter covers the ways to visit every element of a collection, what Iterable is, and the errors that come from iterating carelessly.
Iterable is the common contract
Iterable<E> is the abstract type for "a sequence of E values you can step through one at a time". It declares an iterator getter, and everything else (for-in, first, contains, where, toList) builds on that.
List and Set both implement Iterable. A Map does not. A map holds pairs, so Dart gives you three iterable views of it instead:
map.keysis anIterable<K>.map.valuesis anIterable<V>.map.entriesis anIterable<MapEntry<K, V>>.
Because of this shared contract, a function that only reads elements should accept Iterable<T>. It then works with lists, sets, and map views without copying.
int sum(Iterable<int> numbers) {
var total = 0;
for (final n in numbers) {
total += n;
}
return total;
}
void main() {
print(sum([1, 2, 3])); // 6
print(sum({4, 5, 6})); // 15
print(sum({'a': 10, 'b': 20}.values)); // 30
}The for-in loop
for-in is the default way to visit every element. It works on any Iterable, and it never exposes an index, so it cannot go out of range.
void main() {
final fruits = ['apple', 'banana', 'cherry'];
for (final fruit in fruits) {
print(fruit);
}
}Declare the loop variable with final unless you need to reassign it. Inside the loop body you can use break to stop early and continue to skip to the next element.
When you need the position, use a classic indexed for loop. This only works on a List, because sets have no index.
void main() {
final fruits = ['apple', 'banana', 'cherry'];
for (var i = 0; i < fruits.length; i++) {
print('$i: ${fruits[i]}');
}
}forEach
Iterable.forEach takes a function and calls it once per element. Map.forEach is similar but passes the key and the value as two arguments.
void main() {
final fruits = ['apple', 'banana'];
fruits.forEach(print); // passes each element to print
final stock = {'apple': 3, 'pear': 0};
stock.forEach((name, qty) => print('$name: $qty'));
}forEach reads well for a single function call, but it has three limits that for-in does not:
- You cannot
breakorcontinue. Areturninside the callback only ends that one call, and the next element is still visited. - You cannot
awaitinside it in a useful way, as shown below. - A thrown exception behaves the same, but stack traces are one frame deeper, which makes them harder to read.
The async trap
If the callback is async, forEach starts every call and does not wait for any of them. It returns void, so there is nothing to await.
Future<void> save(int id) async {
await Future<void>.delayed(const Duration(milliseconds: 10));
print('saved $id');
}
Future<void> main() async {
final ids = [1, 2, 3];
ids.forEach(save);
print('after forEach'); // prints before any "saved"
await Future<void>.delayed(const Duration(milliseconds: 50));
for (final id in ids) {
await save(id); // each call finishes before the next starts
}
print('after for-in');
}Use for-in whenever the loop body contains await. To run the calls in parallel and wait for all of them, use Future.wait(ids.map(save)) instead.
Iterating over maps
You have four common choices. Pick the one that gives you exactly what you use.
void main() {
final stock = {'apple': 3, 'pear': 0, 'plum': 5};
for (final entry in stock.entries) {
print('${entry.key} -> ${entry.value}');
}
for (final name in stock.keys) {
print(name);
}
var units = 0;
for (final qty in stock.values) {
units += qty;
}
print(units); // 8
// Dart 3 pattern: unpack key and value in the loop header.
for (final MapEntry(:key, :value) in stock.entries) {
print('$key has $value');
}
}Iterating over stock.keys and then calling stock[name] inside the loop works, but it repeats a lookup and gives a nullable result. entries avoids both.
Map literals keep insertion order, so these loops visit entries in the order you added them. The chapter on ordering variants covers when you need sorted keys instead.
Choosing a loop
| Need | Use |
|---|---|
| Visit every element, maybe stop early | `for (final x in items)` with `break` |
| Need the index | `for (var i = 0; i < list.length; i++)` |
| Call one existing function per element | `items.forEach(fn)` |
| Key and value of a map | `for (final e in map.entries)` or `map.forEach` |
| `await` inside the body | `for-in` |
| Produce a new collection | `where`, `map`, `toList` (next chapters) |
Modifying a collection while iterating
A for-in loop on a List or Set checks, on each step, whether the collection changed size since the loop began. If it did, Dart throws ConcurrentModificationError. Adding or removing map keys during iteration over its keys, values, or entries throws the same error.
void main() {
final items = [1, 2, 3, 4];
try {
for (final n in items) {
if (n.isEven) items.remove(n); // changes length mid-loop
}
} on ConcurrentModificationError {
print('modified during iteration');
}
items.removeWhere((n) => n.isEven);
print(items); // [1, 3]
}There are three safe patterns:
- Use a bulk method such as
removeWhereorretainWhere, which does the loop internally. - Iterate over a copy, for example
for (final n in [...items]), and change the original. - Collect the changes in a second list, then apply them after the loop ends.
Changing an element's contents without changing the collection's length is allowed. For example, assigning items[0] = 10 inside a loop over items does not throw.
Lazy iterables and repeated work
Many Iterable methods return a lazy iterable, not a list. A lazy iterable stores the recipe and runs it each time you iterate. This matters when the recipe has a cost or side effects.
void main() {
var calls = 0;
final odd = [1, 2, 3, 4].where((n) {
calls++;
return n.isOdd;
});
print(calls); // 0, nothing has run yet
print(odd.toList()); // [1, 3]
print(calls); // 4
print(odd.length); // 2, the filter runs again to count
print(calls); // 8
}If you loop over the same lazy iterable several times, call toList() or toSet() once and reuse the result. Also avoid side effects inside where callbacks, because you cannot predict how many times they run.
Useful Iterable members
Several members read the elements without a loop of your own:
isEmptyandisNotEmptytest for content. Prefer them overlength == 0, becauselengthon a lazy iterable walks the whole sequence.contains(x),any(test), andevery(test)answer yes-or-no questions and stop as soon as the answer is known.first,last, andsinglereturn one element. All three throwStateErroron an empty iterable, andsinglealso throws if there is more than one element.firstOrNull,lastOrNull, andsingleOrNull(Dart 3.0 and later) returnnullinstead of throwing.take(n)andskip(n)give the firstnelements or everything after them, lazily.elementAt(i)reads by position on any iterable. On aList,list[i]is the idiomatic and faster form.
void main() {
final names = <String>[];
print(names.firstOrNull); // null
// print(names.first); // would throw StateError: No element
final nums = [5, 3, 8, 1];
print(nums.any((n) => n > 7)); // true
print(nums.every((n) => n > 0)); // true
print(nums.take(2)); // (5, 3)
print(nums.skip(2)); // (8, 1)
}Iterating nullable collections
A loop cannot run over a nullable collection directly, because List<int>? is not an Iterable. Supply a fallback with ??, which is usually better than forcing the value with !.
void printAll(List<String>? names) {
for (final name in names ?? const <String>[]) {
print(name);
}
}
void main() {
printAll(['Ada', 'Grace']);
printAll(null); // prints nothing
}Using the Iterator directly
for-in is shorthand for the Iterator protocol. An iterator starts before the first element. moveNext() advances and returns false when the elements run out. current reads the element at that position.
void main() {
final it = ['a', 'b', 'c'].iterator;
while (it.moveNext()) {
print(it.current);
}
}You rarely write this yourself. It is useful when you need to consume the first element differently from the rest, or pull elements in step with another source.
Common mistakes
- Using
forEachwithasynccallbacks. Nothing waits. Usefor-inwithawait. - Removing elements inside
for-in. UseremoveWhereor iterate a copy. - Reading
firston a possibly empty iterable. UsefirstOrNull, or checkisEmptyfirst. - Re-iterating a lazy iterable with a costly callback. Convert to a list once.
- Looking up
map[key]inside a loop over keys. Iterateentriesand skip the nullable lookup.
Exercise
A function receives Map<String, int> scores and must print only the names whose score is at least 50, stopping at the first score below 10. Which loop do you use, and why not forEach?
Show answer
Use for (final entry in scores.entries) with if (entry.value < 10) break; and a check if (entry.value >= 50) print(entry.key);. forEach cannot break, because return inside its callback only ends the current call and the loop continues with the next entry.
Exercise
What does this code do, and how do you fix it? final tasks = ['a', 'b', 'c']; for (final t in tasks) { if (t == 'b') tasks.add('d'); }
Show answer
It throws ConcurrentModificationError on the step after 'b', because the list length changed during iteration. Fix it by iterating over a copy (for (final t in [...tasks])), or by collecting new items in a separate list and calling tasks.addAll(extra) after the loop.