map
- Dart course
- Intermediate
- Lesson 47/116
- 5 min
Learn transformation with .map.
The map method
The map method transforms each element of a collection and produces a new collection. The original list does not change; the result is a new Iterable.
Example: var doubled = [1, 2, 3].map((n) => n * 2);. Here each number is doubled. The result is [2, 4, 6]. (n) => n * 2 is an arrow function that runs for each element.
map is lazy; to see the result you convert it with toList(). This method is the most common tool for reshaping data.
Transforming with map
The map method takes an arrow function. This function is called for each element and its return value is added to the new collection. You can also change the element type.
Example: var names = ['alex', 'mia'];. var upper = names.map((s) => s.toUpperCase());. Result: ['ALEX', 'MIA']. Here String elements are uppercased.
Another example: var lengths = names.map((s) => s.length);. This turns Strings into ints. map is flexible; the output type depends on the arrow function you provide.
Practice Double the numbers
Call map on the list [1, 2, 3]. The arrow function should be (n) => n * 2. Convert the result to a list with toList() and print it.
Starter code
void main() {
var numbers = [1, 2, 3];
// use .map to double each element, convert with toList and print
}Sample solution
void main() {
var numbers = [1, 2, 3];
var doubled = numbers.map((n) => n * 2);
print(doubled.toList());
}Expected output
[2, 4, 6]
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Does map modify the original list?
var a = [1, 2, 3];
var b = a.map((n) => n * 2);- Yes, it mutates in place
- It only prints
- No, it returns a new Iterable Correct answer
- It deletes the list
Explanation: map does not modify the original, it returns a new Iterable.
2 The map call
var numbers = [1, 2, 3];
var doubled = numbers.____((n) => n * 2);
var numbers = [1, 2, 3];
var doubled = numbers.map((n) => n * 2);
Explanation: map transforms each element.
3 Match the map parts
| Term | Meaning |
|---|---|
(n) => n * 2 |
Arrow function |
.map(...) |
Transform call |
.toList() |
Materialize result |
[2, 4, 6] |
Transformed result |