Iterators
suggest changeEvery for-in loop over a List, Set, map's keys or a generator is driven by two small interfaces from dart:core:
Iterable<E>is a sequence that can be walked, any number of times. It has a single abstract member,Iterator<E> get iterator, and provides about 40 methods (map,where,first,length,toList, ...) built on top of it.Iterator<E>is one walk over that sequence. It has justbool moveNext()andE get current.
List, Set, Queue, Map.keys, Map.values, Map.entries, String.runes and the results of map/where are all Iterables. Map and String themselves are not.
This article shows how the protocol works, how to implement it, how the lazy Iterable methods behave, and how to drive iterators by hand. For writing iterables with sync* and yield see Sync and async generators. The examples were run with Dart 3.13.
The iterator protocol
To walk a sequence, ask the Iterable for an iterator and call moveNext() until it returns false. After each successful moveNext(), the element is in current:
void main() {
final fruits = ['apple', 'banana', 'cherry'];
final it = fruits.iterator;
while (it.moveNext()) {
print(it.current);
}
print('moveNext after the end: ${it.moveNext()}');
// the same loop, written with for-in
for (final f in fruits) {
print(f.toUpperCase());
}
}
Output:
apple
banana
cherry
moveNext after the end: false
APPLE
BANANA
CHERRY
for (final f in fruits) { ... } is exactly the while (it.moveNext()) loop above, with final f = it.current; as the first statement of the body.
Rules of the protocol:
- a new iterator is positioned before the first element; you must call
moveNext()before readingcurrent, - once
moveNext()returnsfalseit keeps returningfalse, - reading
currentbefore the firstmoveNext()or after the end is not allowed. What happens depends on the implementation: aList<int>iterator throwstype 'Null' is not a subtype of type 'int', aList<int?>iterator returnsnull, - an iterator can't be reset. Call
iteratoragain to start over.
Implementing Iterator and Iterable
To make your own type iterable, implement Iterator<E> and extend Iterable<E>, overriding only iterator. Everything else (for-in, map, where, length, toString, ...) comes for free:
class CountdownIterator implements Iterator<int> {
int _next;
int? _current;
CountdownIterator(int from) : _next = from;
@override
int get current => _current ?? (throw StateError('no current element'));
@override
bool moveNext() {
if (_next <= 0) {
_current = null;
return false;
}
_current = _next--;
return true;
}
}
class Countdown extends Iterable<int> {
final int from;
const Countdown(this.from);
@override
Iterator<int> get iterator => CountdownIterator(from);
}
void main() {
const c = Countdown(5);
for (final n in c) {
print(n);
}
print(c.toList());
print(c.where((n) => n.isOdd).map((n) => n * 10));
print('length=${c.length} first=${c.first} last=${c.last}');
print(c.contains(3));
final it = c.iterator;
try {
print(it.current);
} on StateError catch (e) {
print(e);
}
}
Output:
5
4
3
2
1
[5, 4, 3, 2, 1]
(50, 30, 10)
length=5 first=5 last=1
true
Bad state: no current element
The Iterable stores only the description of the sequence (from). All mutable state (where we are) lives in the iterator, and each call to iterator returns a fresh one. That's what lets c be iterated many times, and by several loops at once.
If your class already extends another class, mix the methods in instead: class Countdown extends Base with Iterable<int>. IterableBase from dart:collection is the same thing under an older name.
Writing iterator classes by hand is verbose. Usually a sync* method does the job in a few lines: Iterator<int> get iterator => _values().iterator;. The generators article has a full example. Hand-written iterators are still worth it when you need maximum speed or want to override other members, as in the next section.
Overriding members for speed
The default length, elementAt, contains and last iterate from the start, which is O(n). If your type can answer them directly, override them:
/// Integers from [start] (inclusive) to [end] (exclusive), by [step].
class Range extends Iterable<int> {
final int start, end, step;
Range(this.start, this.end, [this.step = 1])
: assert(step > 0);
@override
Iterator<int> get iterator => _RangeIterator(this);
// O(1) instead of walking the whole range
@override
int get length => end <= start ? 0 : (end - start + step - 1) ~/ step;
@override
int elementAt(int index) {
RangeError.checkValidIndex(index, this);
return start + index * step;
}
@override
bool contains(Object? x) =>
x is int && x >= start && x < end && (x - start) % step == 0;
}
class _RangeIterator implements Iterator<int> {
final Range _r;
int _next;
int _current = 0;
_RangeIterator(this._r) : _next = _r.start;
@override
int get current => _current;
@override
bool moveNext() {
if (_next >= _r.end) return false;
_current = _next;
_next += _r.step;
return true;
}
}
void main() {
final r = Range(0, 1000000000, 3);
print(r.length);
print(r.elementAt(1000));
print(r.contains(999999999));
print(r.take(5).toList());
print(r.skip(10).first);
print(Range(5, 15, 4));
try {
r.elementAt(-1);
} on RangeError catch (e) {
print(e.message);
}
}
Output:
333333334
3000
true
[0, 3, 6, 9, 12]
30
(5, 9, 13)
Index out of range
The range describes a third of a billion numbers but uses three fields of memory, and length, elementAt and contains return instantly. See Ranges for other ways to produce number sequences.
Lazy Iterable methods
Most Iterable methods that return an Iterable (map, where, expand, skip, take, skipWhile, takeWhile, followedBy, whereType, cast) don't compute anything. They return a lazy wrapper that does the work when it is iterated, and only as far as it is iterated:
void main() {
final numbers = [1, 2, 3, 4, 5, 6];
final pipeline = numbers.where((n) {
print(' where($n)');
return n.isEven;
}).map((n) {
print(' map($n)');
return n * n;
});
print('pipeline built, is List: ${pipeline is List}');
print('first: ${pipeline.first}');
print('toList: ${pipeline.toList()}');
}
Output:
pipeline built, is List: false
where(1)
where(2)
map(2)
first: 4
where(1)
where(2)
map(2)
where(3)
where(4)
map(4)
where(5)
where(6)
map(6)
toList: [4, 16, 36]
Building the pipeline printed nothing. first pulled elements one at a time through both stages and stopped as soon as it had one result. toList() ran the whole pipeline again from the beginning: a lazy iterable doesn't cache its results.
Because it is a view, a lazy iterable sees later changes to its source:
void main() {
final scores = [70, 85, 92];
final passed = scores.where((s) => s >= 80); // a view, not a copy
final snapshot = passed.toList(); // a copy, computed now
scores.add(99);
scores[0] = 81;
print(passed);
print(snapshot);
}
Output:
(81, 85, 92, 99)
[85, 92]
Practical consequences:
- call
toList()(ortoSet()) when you will iterate the result more than once, when the callbacks are expensive or have side effects, or when the source may change, length,lastandelementAton a lazy iterable walk it, sofor (var i = 0; i < xs.length; i++) xs.elementAt(i)on awhereresult is O(n²),- a lazy iterable prints with parentheses,
(1, 2), aListwith brackets,[1, 2]. That's a quick hint when debugging, - when a function returns
Iterable<T>, callers shouldn't assume it is cheap to iterate twice.
Methods that return something other than an Iterable are eager and consume the sequence immediately: toList, toSet, length, first, last, single, elementAt, contains, any, every, fold, reduce, join, forEach, firstWhere.
Combining and reducing
The Iterable API covers most loops you would otherwise write by hand:
void main() {
final orders = [
(id: 1, items: ['pen', 'ink']),
(id: 2, items: <String>[]),
(id: 3, items: ['paper', 'pen', 'clip']),
];
final allItems = orders.expand((o) => o.items);
print(allItems.toList());
print(allItems.toSet());
final head = [1, 2, 3];
print(head.followedBy([4, 5]).followedBy(Iterable.generate(3, (i) => 10 * i)));
final readings = [0, 0, 3, 7, 12, 4, 0, 9];
print(readings.skipWhile((r) => r == 0).takeWhile((r) => r != 0).toList());
print(readings.skip(2).take(3).toList());
print(readings.any((r) => r > 10));
print(readings.every((r) => r >= 0));
print(readings.reduce((a, b) => a > b ? a : b));
print(readings.fold<int>(0, (sum, r) => sum + r));
print(readings.where((r) => r > 0).join(' + '));
print(Iterable<int>.generate(5, (i) => i * i).toList());
print(Iterable<String>.empty().isEmpty);
print(List.filled(3, '-').join());
}
Output:
[pen, ink, paper, pen, clip]
{pen, ink, paper, clip}
(1, 2, 3, 4, 5, 0, 10, 20)
[3, 7, 12, 4]
[3, 7, 12]
true
true
12
35
3 + 7 + 12 + 4 + 9
[0, 1, 4, 9, 16]
true
---
expandmaps each element to an iterable and flattens the results (flatMap in other languages),followedByconcatenates lazily, without copying either side,reducethrows on an empty iterable;foldtakes a starting value and works on empty input. Givefoldan explicit type argument (fold<int>) when the result type can't be inferred from the initial value,Iterable.generate(n, f)is a lazy sequence off(0)...f(n - 1).
For transforming individual collections see Map each element in the collection and Filter a list.
Finding elements safely
first, last, single, firstWhere and reduce throw a StateError when there is no answer. The IterableExtensions in dart:core add null-returning versions:
void main() {
final words = ['kiwi', 'fig', 'banana', 'apple', 'date'];
final empty = <String>[];
print(words.firstWhere((w) => w.length > 4));
print(words.lastWhere((w) => w.length == 4));
print(words.firstWhere((w) => w.startsWith('z'), orElse: () => 'none'));
print(empty.firstOrNull);
print(words.lastOrNull);
print(words.elementAtOrNull(10));
print(words.where((w) => w.startsWith('z')).firstOrNull);
print(['fig'].singleOrNull);
print(words.singleOrNull);
try {
print(empty.first);
} on StateError catch (e) {
print(e);
}
try {
print(words.single);
} on StateError catch (e) {
print(e);
}
final mixed = <Object?>[1, 'two', null, 3.0, 4, null];
print(mixed.whereType<int>().toList());
print(mixed.nonNulls.toList());
}
Output:
banana
date
none
null
date
null
null
fig
null
Bad state: No element
Bad state: Too many elements
[1, 4]
[1, two, 3.0, 4]
where(...).firstOrNull is the idiomatic "find or null". It is lazy, so it stops at the first match just like firstWhere. whereType<T>() filters and changes the static type in one step; nonNulls turns an Iterable<T?> into an Iterable<T>. More on nullable types in Null safety.
Indexes and maps
An Iterable has no index, but indexed pairs each element with its position as a record. On a List, a classic counting loop also works, and asMap() gives an index-to-element view:
void main() {
final colors = ['red', 'green', 'blue'];
for (final (i, c) in colors.indexed) {
print('$i: $c');
}
for (var i = 0; i < colors.length; i++) {
if (i > 0) colors[i] = colors[i].toUpperCase(); // replacing is fine
}
print(colors);
print(colors.asMap());
final stock = {'apples': 3, 'pears': 0, 'plums': 12};
for (final MapEntry(:key, :value) in stock.entries) {
print('$key -> $value');
}
print(stock.keys.where((k) => stock[k]! > 0).toList());
print(stock.values.fold<int>(0, (sum, v) => sum + v));
print(Map.fromEntries(stock.entries.where((e) => e.value > 0)));
}
Output:
0: red
1: green
2: blue
[red, GREEN, BLUE]
{0: red, 1: GREEN, 2: BLUE}
apples -> 3
pears -> 0
plums -> 12
[apples, plums]
15
{apples: 3, plums: 12}
A Map is not an Iterable. Iterate over keys, values or entries; the MapEntry(:key, :value) pattern destructures each entry (see Destructuring). Iterating entries is better than looking up stock[k] for each key, which does a second hash lookup and needs !. The default Map (a LinkedHashMap) and Set iterate in insertion order.
Modifying a collection while iterating
Adding or removing elements from a List, Set or Map while iterating over it makes the iterator throw ConcurrentModificationError on its next step. Replacing a list element (list[i] = x) or updating the value of an existing map key is allowed, because the length doesn't change:
void main() {
final names = ['ann', 'bob', 'cid', 'dee'];
try {
for (final n in names) {
if (n.startsWith('b')) names.remove(n);
}
} on ConcurrentModificationError catch (e) {
print(e);
}
print(names);
final tags = {'a', 'bb', 'ccc'};
try {
for (final t in tags) {
if (t.length > 1) tags.add(t.toUpperCase());
}
} on ConcurrentModificationError catch (e) {
print(e.runtimeType);
}
// safe alternatives
final list = ['ann', 'bob', 'cid', 'dee'];
list.removeWhere((n) => n.startsWith('b') || n.startsWith('d'));
print(list);
final set = {'a', 'bb', 'ccc'};
for (final t in set.toList()) {
if (t.length > 1) set.add(t.toUpperCase());
}
print(set);
final ages = {'ann': 31, 'bob': 17, 'cid': 45};
ages.removeWhere((name, age) => age < 18);
ages.updateAll((name, age) => age + 1);
print(ages);
}
Output:
Concurrent modification during iteration: Instance(length:3) of '_GrowableList'.
[ann, cid, dee]
ConcurrentModificationError
[ann, cid]
{a, bb, ccc, BB, CCC}
{ann: 32, cid: 46}
Note that the element was removed before the error was thrown, so after catching it the list is in a half-processed state. Don't catch this error; fix the loop:
- use
removeWhere/retainWhereon lists, sets and maps, - iterate over a copy (
toList()) when the body needs to add elements, - build a new collection with
where/mapor a collection-forinstead of mutating in place, - remember that lazy views count too: removing from
scoreswhile iteratingscores.where(...)throws the same error.
Driving iterators by hand
for-in walks one sequence. To walk two sequences in step, or to look at neighbouring elements, use their iterators directly. Wrapping the logic in a sync* function keeps the result lazy:
Iterable<(A, B)> zip<A, B>(Iterable<A> a, Iterable<B> b) sync* {
final ia = a.iterator;
final ib = b.iterator;
while (ia.moveNext() && ib.moveNext()) {
yield (ia.current, ib.current);
}
}
Iterable<int> mergeSorted(Iterable<int> a, Iterable<int> b) sync* {
final ia = a.iterator;
final ib = b.iterator;
var hasA = ia.moveNext();
var hasB = ib.moveNext();
while (hasA && hasB) {
if (ia.current <= ib.current) {
yield ia.current;
hasA = ia.moveNext();
} else {
yield ib.current;
hasB = ib.moveNext();
}
}
while (hasA) {
yield ia.current;
hasA = ia.moveNext();
}
while (hasB) {
yield ib.current;
hasB = ib.moveNext();
}
}
extension Windows<T> on Iterable<T> {
Iterable<(T, T)> pairwise() sync* {
final it = iterator;
if (!it.moveNext()) return;
var prev = it.current;
while (it.moveNext()) {
yield (prev, it.current);
prev = it.current;
}
}
Iterable<List<T>> chunked(int size) sync* {
final it = iterator;
while (it.moveNext()) {
final chunk = [it.current];
while (chunk.length < size && it.moveNext()) {
chunk.add(it.current);
}
yield chunk;
}
}
}
void main() {
final names = ['ann', 'bob', 'cid'];
final ages = [31, 17, 45, 60];
for (final (name, age) in zip(names, ages)) {
print('$name is $age');
}
print(mergeSorted([1, 4, 9, 10], [2, 3, 11]).toList());
final temps = [12, 15, 14, 18, 21];
print(temps.pairwise().map((p) => p.$2 - p.$1).toList());
print(Iterable.generate(7, (i) => i).chunked(3).toList());
}
Output:
ann is 31
bob is 17
cid is 45
[1, 2, 3, 4, 9, 10, 11]
[3, -1, 4, 3]
[[0, 1, 2], [3, 4, 5], [6]]
zip stops at the shorter input. mergeSorted keeps a hasA/hasB flag because current may not be read after moveNext() returns false. All of these walk each input exactly once, so they also work on inputs that are expensive to iterate or infinite. Defining them as extension methods makes them chain like the built-in ones. package:collection ships ready-made versions of many such helpers (slices, splitBefore, mapIndexed, ...).
Strings and runes
A String is not an Iterable. Pick the view that matches what you mean by "character":
void main() {
const s = 'Dart 🎯';
print(s is Iterable);
print(s.length);
print(s.codeUnits);
print(s.runes.toList());
print(s.runes.length);
print(s.runes.map(String.fromCharCode).toList());
print(s.split(''));
final it = s.runes.iterator;
while (it.moveNext()) {
print('${it.rawIndex}: ${it.currentAsString}');
}
}
Output:
false
7
[68, 97, 114, 116, 32, 55356, 57263]
[68, 97, 114, 116, 32, 127919]
6
[D, a, r, t, , 🎯]
[D, a, r, t, , �, �]
0: D
1: a
2: r
3: t
4:
5: 🎯
codeUnits are UTF-16 units, so the emoji counts as two and split('') cuts it in half. runes yields Unicode code points, and its RuneIterator adds rawIndex (the code-unit offset) and currentAsString. For user-perceived characters (emoji with skin tones, flags, combining accents) use package:characters. Details are in Unicode and encodings.
Summary
Iterabledescribes a sequence and can be walked many times;Iteratoris a single walk withmoveNext()andcurrent.for-in is sugar for themoveNext()loop.- Read
currentonly aftermoveNext()returnedtrue. - Implement
iteratorand extend (or mix in)Iterable<E>to get the full API for free; overridelength,elementAtandcontainswhen you can do better than O(n). Use async*generator to avoid writing the iterator class. map,where,expand,take,skipand friends are lazy views: they run on every iteration and see changes to the source. CalltoList()to compute once.- Use
firstOrNull,where(...).firstOrNull,whereTypeandnonNullsinstead of catchingStateError. - Don't add or remove elements of a collection while iterating it; use
removeWhereor iterate a copy. - For asynchronous sequences the equivalent of
IterableisStream, consumed withawait for; see Sync and async generators and Async and Await.