DartBasic 2 min read

Dart collections: where, map and fold

Use where, map and fold to filter data, create labels and calculate a result without mutating the original list.

On this page

A collection pipeline can describe a transformation in the order you think about it: keep the relevant items, turn them into the form you need, then collect or reduce the results.

Filter, transform, collect

main.dart
void main() {
  final durations = [5, 20, 10, 30, 15];
  final shortSessions = durations.where((minutes) => minutes <= 15);
  final labels = shortSessions.map((minutes) => '$minutes min').toList();
  final total = shortSessions.fold<int>(0, (sum, minutes) => sum + minutes);

  print(labels);
  print('Total: $total minutes');
  print('Original: $durations');
}

Know when work happens

Many Iterable transformations are lazy: they describe work that runs when the result is iterated. toList materializes a list. Reiterating a lazy transformation can repeat its callbacks.

Keep those callbacks free of surprising side effects. A callback that sends a network request or increments a global counter can behave unexpectedly if the iterable is read twice.

A loop is still a good tool

Use a straightforward loop when it makes branching or early exit clearer. The goal is readable intent, not the highest number of chained methods.

Know what is lazy and what becomes a stored result

where and map describe iterable transformations. Iterating them performs their callbacks. toList materializes a list at that point, while fold walks the values to produce one accumulated result.

Because a lazy iterable can be read again, callbacks with surprising side effects can run more than once. Prefer pure filtering and formatting in a pipeline, and use a clear loop when branching or early exit makes the intent easier to follow.

Compare the source list before and after the example. It should be unchanged. Then use a model class instead of bare durations to filter sessions by several meaningful fields.

Try it yourself

Create labels only for sessions between ten and twenty minutes. Then calculate the longest session with an explicit policy for an empty input. Keep the original collection unchanged.

How this topic connects

Understand first

Apply it next

Lesson progressMark complete after checking the example and exercise.

Find your next idea

Search lessons, code examples and projects.

Type a few words to start exploring.