The syntax of List.map() method is:
Iterable<T> map<T>(T toElement(E e))
This map() method of List the current elements of this iterable modified by toElement
.
Parameter | Optional/Required | Description |
---|---|---|
toElement | required | a function that transforms each element of the iterable |
List.map() returns value of type Iterable<T>
.
In this example,
numbers
containing the integers [1, 2, 3, 4, 5]
.map()
method to transform each integer into a string representation with the format 'Number: number'.toList()
method converts the resulting iterable into a list.void main() {
List<int> numbers = [1, 2, 3, 4, 5];
List<String> stringNumbers = numbers.map((e) => 'Number: $e').toList(); // Output: ['Number: 1', 'Number: 2', 'Number: 3', 'Number: 4', 'Number: 5']
print(stringNumbers);
}
[Number: 1, Number: 2, Number: 3, Number: 4, Number: 5]
In this example,
characters
containing the characters ['a', 'b', 'c']
.map()
method to transform each character to its uppercase equivalent.toList()
method converts the resulting iterable into a list.void main() {
List<String> characters = ['a', 'b', 'c'];
List<String> upperCaseCharacters = characters.map((e) => e.toUpperCase()).toList(); // Output: ['A', 'B', 'C']
print(upperCaseCharacters);
}
[A, B, C]
In this example,
words
containing the strings ['apple', 'banana', 'cherry']
.map()
method to transform each string to its length.toList()
method converts the resulting iterable into a list.void main() {
List<String> words = ['apple', 'banana', 'cherry'];
List<int> wordLengths = words.map((e) => e.length).toList(); // Output: [5, 6, 6]
print(wordLengths);
}
[5, 6, 6]
In this Dart tutorial, we learned about map() method of List: the syntax and few working examples with output and detailed explanation for each example.