List methods
- Dart course
- Beginner
- Lesson 57/116
- 5 min
Learn list processing with map, where and fold.
List methods
In Dart three common methods transform and query a List: map transforms each element, where filters elements, fold reduces all elements to a single value. All three return a new Iterable; to use as a List call .toList().
For example [1, 2, 3].map((x) => x * 2).toList() returns [2, 4, 6]. (x) => x * 2 is an arrow function; it runs for each element and produces x * 2. You will see more about arrow functions in a later level.
map, where, fold
map transforms each element: [1, 2, 3].map((x) => x * 2) returns [2, 4, 6]. where filters by a condition: [1, 2, 3].where((x) => x > 1) returns [2, 3]. fold combines all elements with a starting value: [1, 2, 3].fold(0, (a, b) => a + b) returns 6.
map and where return an Iterable; call .toList() for a List. fold returns a single value directly; no .toList() needed. The arrow function is written (param) => expression.
Practice Double each element with map
Declare a List with var numbers = [1, 2, 3];. Declare a variable doubled and assign the result of numbers.map((x) => x * 2).toList() to it (map returns an Iterable; convert with .toList()). Print doubled with print(doubled);. The output on a single line must be [2, 4, 6].
Starter code
// Declare numbers, double each with map (convert with toList) and printSample solution
var numbers = [1, 2, 3];
var doubled = numbers.map((x) => x * 2).toList();
print(doubled);Expected output
[2, 4, 6]
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match each method to its job
| Term | Meaning |
|---|---|
map |
Transforms each element |
where |
Filters elements |
fold |
Produces a single value |
.toList() |
Converts Iterable to List |
2 What does the map method do?
[1, 2, 3].map((x) => x * 2)- Sorts the list
- Filters elements
- Produces a single value
- Transforms each element Correct answer
Explanation: map transforms each element with the given function.
3 Write the map call
var numbers = [1, 2, 3];
var doubled = numbers____;
print(doubled);
var numbers = [1, 2, 3];
var doubled = numbers.map((x) => x * 2).toList();
print(doubled);
Explanation: map returns an Iterable; .toList() converts it to a List.