Dart List asMap()
Syntax & Examples


Syntax of List.asMap()

The syntax of List.asMap() method is:

 Map<int, E> asMap() 

This asMap() method of List an unmodifiable Map view of this list.

Return Type

List.asMap() returns value of type Map<int, E>.



✐ Examples

1 Create a map from a list of numbers

In this example,

  1. We create a list named numbers containing the integers 1, 2, 3.
  2. We apply the asMap() method on numbers to create a map where the indices of numbers are the keys and the corresponding elements are the values.
  3. The resulting map is printed to standard output.

Dart Program

void main() {
  List&lt;int&gt; numbers = [1, 2, 3];
  Map&lt;int, int&gt; map = numbers.asMap();
  print('Map from numbers: $map'); // Output: Map from numbers: {0: 1, 1: 2, 2: 3}
}

Output

Map from numbers: {0: 1, 1: 2, 2: 3}

2 Create a map from a list of characters

In this example,

  1. We create a list named characters containing the characters 'a', 'b', 'c'.
  2. We apply the asMap() method on characters to create a map where the indices of characters are the keys and the corresponding elements are the values.
  3. The resulting map is printed to standard output.

Dart Program

void main() {
  List&lt;String&gt; characters = ['a', 'b', 'c'];
  Map&lt;int, String&gt; map = characters.asMap();
  print('Map from characters: $map'); // Output: Map from characters: {0: a, 1: b, 2: c}
}

Output

Map from characters: {0: a, 1: b, 2: c}

3 Create a map from a list of strings

In this example,

  1. We create a list named fruits containing the strings 'apple', 'banana', 'cherry'.
  2. We apply the asMap() method on fruits to create a map where the indices of fruits are the keys and the corresponding elements are the values.
  3. The resulting map is printed to standard output.

Dart Program

void main() {
  List&lt;String&gt; fruits = ['apple', 'banana', 'cherry'];
  Map&lt;int, String&gt; map = fruits.asMap();
  print('Map from fruits: $map'); // Output: Map from fruits: {0: apple, 1: banana, 2: cherry}
}

Output

Map from fruits: {0: apple, 1: banana, 2: cherry}

Summary

In this Dart tutorial, we learned about asMap() method of List: the syntax and few working examples with output and detailed explanation for each example.