TExcelTAD
Home › Dart › Dart Iterables

Dart Iterables

Iterable<E> is the common interface behind lists, sets, map keys and values, and many other sequences. It provides a rich toolbox of functional methods — map, where, fold, expand, any, every, take, skip and more — that let you transform data without writing loops by hand.

Iterables are lazy

Methods such as map and where return a lazy Iterable: nothing is computed until you iterate over it (with for, toList(), first, etc.). And it is recomputed on every iteration.

dart · try it yourself
void main() {
  final numbers = [1, 2, 3, 4];

  final doubled = numbers.map((n) {
    print('  mapping $n');
    return n * 2;
  });

  print('nothing mapped yet');
  print(doubled.first);   // maps only the first element
  print(doubled.toList()); // maps all four
  print(doubled);         // printing iterates again!
}
nothing mapped yet
  mapping 1
2
  mapping 1
  mapping 2
  mapping 3
  mapping 4
[2, 4, 6, 8]
  mapping 1
  mapping 2
  mapping 3
  mapping 4
(2, 4, 6, 8)

Tip: Call .toList() once if you'll iterate the result several times or if the mapping function is expensive or has side effects. Notice too that an Iterable prints with ( ), a List with [ ].

Transforming and filtering

Method Returns Purpose
map(f) Iterable<T> Transform each element
where(test) Iterable<E> Keep matching elements
whereType<T>() Iterable<T> Keep elements of a type
expand(f) Iterable<T> Map each element to several (flatten)
take(n), skip(n) Iterable<E> First n / all but first n
takeWhile, skipWhile Iterable<E> Take/skip while a test holds
followedBy(other) Iterable<E> Concatenate
dart · try it yourself
void main() {
  final orders = [
    (id: 1, customer: 'Ha', total: 250),
    (id: 2, customer: 'Son', total: 80),
    (id: 3, customer: 'Ha', total: 40),
    (id: 4, customer: 'Mai', total: 500),
  ];

  final bigOrderIds = orders.where((o) => o.total >= 100).map((o) => o.id);
  print(bigOrderIds.toList());

  final customers = orders.map((o) => o.customer).toSet();
  print(customers);

  final mixed = <Object>[1, 'two', 3.0, 4, 'five'];
  print(mixed.whereType<int>().toList());

  final tagLists = [['dart', 'web'], ['cli'], []];
  print(tagLists.expand((tags) => tags).toList());

  print([5, 8, 12, 3, 20].takeWhile((n) => n < 10).toList());
  print([1, 2, 3, 4, 5].skip(2).take(2).toList());
}
[1, 4]
{Ha, Son, Mai}
[1, 4]
[dart, web, cli]
[5, 8]
[3, 4]

Reducing to a single value

Method Example result
fold(initial, combine) Any type; safe on empty collections
reduce(combine) Same type as elements; throws on empty
join(sep) A String
any(test) / every(test) bool
length, isEmpty, contains(x) Size and membership
dart · try it yourself
void main() {
  final cart = {'pen': 3, 'notebook': 2, 'bag': 1};
  final prices = {'pen': 5, 'notebook': 12, 'bag': 90};

  final total = cart.entries.fold(0, (sum, e) => sum + e.value * prices[e.key]!);
  print('total: $total');

  final longest = cart.keys.reduce((a, b) => a.length >= b.length ? a : b);
  print('longest name: $longest');

  print(cart.values.any((q) => q > 2));
  print(cart.values.every((q) => q > 0));
  print(cart.keys.join(' | '));

  final empty = <int>[];
  print(empty.fold<int>(0, (a, b) => a + b));
  try {
    empty.reduce((a, b) => a + b);
  } on StateError catch (e) {
    print('reduce failed: ${e.message}');
  }
}
total: 129
longest name: notebook
true
true
pen | notebook | bag
0
reduce failed: No element

Finding elements

first, last and single throw a StateError on an empty iterable. Dart 3 adds null-returning versions in dart:core: firstOrNull, lastOrNull, singleOrNull, plus firstWhere with orElse.

dart · try it yourself
void main() {
  final words = ['kiwi', 'banana', 'cherry', 'fig'];

  print(words.firstWhere((w) => w.startsWith('c')));
  print(words.firstWhere((w) => w.startsWith('z'), orElse: () => 'none'));
  print(words.where((w) => w.length > 10).firstOrNull);
  print(words.lastWhere((w) => w.length == 4));
  print(words.indexWhere((w) => w.contains('an')));

  for (final (i, w) in words.indexed.skip(2)) {
    print('$i=$w');
  }
}
cherry
none
null
kiwi
1
2=cherry
3=fig

Writing your own iterable with a generator

A function marked sync* returns an Iterable and produces values with yield. It's lazy too — values are generated on demand, so infinite sequences are fine as long as you only take a few:

dart · try it yourself
Iterable<int> range(int start, int end, [int step = 1]) sync* {
  for (var i = start; i < end; i += step) {
    yield i;
  }
}

Iterable<int> fibonacci() sync* {
  var (a, b) = (0, 1);
  while (true) {
    yield a;
    (a, b) = (b, a + b);
  }
}

void main() {
  print(range(0, 10, 3).toList());
  print(fibonacci().take(10).toList());
  print(fibonacci().where((n) => n.isEven).skip(1).first);
}
[0, 3, 6, 9]
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
2

yield* delegates to another iterable: yield* range(0, 3); emits all of its values.

Test yourself

When does the function passed to list.map(f) run?

  1. Immediately, for every element
  2. Only when the resulting iterable is iterated
  3. Never
  4. When the list changes

What happens when you call reduce on an empty list?

  1. Returns 0
  2. Returns null
  3. Throws a StateError
  4. Returns an empty list

Which keyword makes a function a synchronous generator?

  1. async
  2. sync*
  3. yield
  4. generator