Dart Tutorials

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

ParameterOptional/RequiredDescription
toElementrequireda 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,

  1. We create a list named numbers containing the integers [1, 2, 3, 4, 5].
  2. We then use the map() method to transform each integer into a string representation with the format 'Number: number'.
  3. The toList() method converts the resulting iterable into a list.
  4. We print the list of string representations to standard output.

Dart Program

void main() {
  List&lt;int&gt; numbers = [1, 2, 3, 4, 5];
  List&lt;String&gt; 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,

  1. We create a list named characters containing the characters ['a', 'b', 'c'].
  2. We then use the map() method to transform each character to its uppercase equivalent.
  3. The toList() method converts the resulting iterable into a list.
  4. We print the list of uppercase characters to standard output.

Dart Program

void main() {
  List&lt;String&gt; characters = ['a', 'b', 'c'];
  List&lt;String&gt; 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,

  1. We create a list named words containing the strings ['apple', 'banana', 'cherry'].
  2. We then use the map() method to transform each string to its length.
  3. The toList() method converts the resulting iterable into a list.
  4. We print the list of string lengths to standard output.

Dart Program

void main() {
  List&lt;String&gt; words = ['apple', 'banana', 'cherry'];
  List&lt;int&gt; 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.