Dart List map()
Syntax & Examples
Syntax of List.map()
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
.
Parameters
Parameter | Optional/Required | Description |
---|---|---|
toElement | required | a function that transforms each element of the iterable |
Return Type
List.map() returns value of type Iterable<T>
.
✐ Examples
1 Map integers to string representation
In this example,
- We create a list named
numbers
containing the integers[1, 2, 3, 4, 5]
. - We then use the
map()
method to transform each integer into a string representation with the format 'Number: number'. - The
toList()
method converts the resulting iterable into a list. - We print the list of string representations to standard output.
Dart Program
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);
}
Output
[Number: 1, Number: 2, Number: 3, Number: 4, Number: 5]
2 Map characters to uppercase
In this example,
- We create a list named
characters
containing the characters['a', 'b', 'c']
. - We then use the
map()
method to transform each character to its uppercase equivalent. - The
toList()
method converts the resulting iterable into a list. - We print the list of uppercase characters to standard output.
Dart Program
void main() {
List<String> characters = ['a', 'b', 'c'];
List<String> upperCaseCharacters = characters.map((e) => e.toUpperCase()).toList(); // Output: ['A', 'B', 'C']
print(upperCaseCharacters);
}
Output
[A, B, C]
3 Map strings to their lengths
In this example,
- We create a list named
words
containing the strings['apple', 'banana', 'cherry']
. - We then use the
map()
method to transform each string to its length. - The
toList()
method converts the resulting iterable into a list. - We print the list of string lengths to standard output.
Dart Program
void main() {
List<String> words = ['apple', 'banana', 'cherry'];
List<int> wordLengths = words.map((e) => e.length).toList(); // Output: [5, 6, 6]
print(wordLengths);
}
Output
[5, 6, 6]
Summary
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.