Sub topic 8
Transforming Data: `where`, `map`, `fold`, and `toList`
This chapter assumes you know Dart variables, functions, generics such as List<int>, and null safety. It focuses on Iterable, Dart's interface for values that can be visited one at a time. Lists, sets, and many collection results implement Iterable.
Transformation methods let you filter, change, or combine collection values without writing an index-based loop.
The transformation pipeline
A common pipeline has three stages:
wherekeeps values that satisfy a condition.mapchanges each remaining value.toListcollects the result into a new list.
For example, this code keeps even numbers and then squares them:
void main() {
final numbers = [1, 2, 3, 4, 5, 6];
final evenSquares = numbers
.where((number) => number.isEven)
.map((number) => number * number)
.toList();
print(evenSquares); // [4, 16, 36]
}The closures passed to where and map are functions. The where closure returns a bool. The map closure returns the new value for each element.
Lazy `Iterable` results
where and map return lazy Iterable objects. Lazy means Dart postpones the work until the iterable is read. Calling these methods does not immediately create a new list.
void main() {
final numbers = [1, 2, 3];
final doubled = numbers.map((number) {
print('Mapping $number');
return number * 2;
});
print('Before reading');
print(doubled.toList());
}The output begins with Before reading. The mapping messages appear when toList() reads the iterable.
Lazy behavior can save memory when you process values one at a time. It can also surprise you if the source collection changes before the iterable is consumed. Call toList() when you need a separate, reusable snapshot.
Reducing values with `fold`
fold processes every element and combines the results into one value. It starts with an initial value called the accumulator.
void main() {
final prices = [12, 8, 15];
final total = prices.fold<int>(
0,
(sum, price) => sum + price,
);
print(total); // 35
}The accumulator starts at 0. For each price, the callback returns the next accumulator value. The generic type argument, <int>, makes the result type clear.
The initial value must match the operation. Use 0 for a sum, 1 for a product, or an empty string for text concatenation.
Common errors
- Forgetting
toList()when an API requiresList<T>instead ofIterable<T>. - Expecting
mapto change the source list. - Using the wrong accumulator type in
fold. - Performing work with side effects inside a lazy pipeline and assuming it runs immediately.
- Calling
wherewith a callback that returns a value instead oftrueor `false.
A pipeline can also start from a set or another iterable:
void main() {
final words = {'Dart', 'Flutter', 'Dart'};
final lengths = words
.where((word) => word.length > 3)
.map((word) => word.length)
.toList();
print(lengths);
}The set removes the duplicate "Dart" before the pipeline runs.
Exercise
What is printed by final result = [2, 4, 5].where((n) => n.isEven).map((n) => n + 1).toList();?
Show answer
[3, 5]. where keeps 2 and 4, and map changes them to 3 and 5.