The syntax of List.asMap() method is:
Map<int, E> asMap()
This asMap() method of List an unmodifiable Map
view of this list.
List.asMap() returns value of type Map<int, E>
.
In this example,
numbers
containing the integers 1, 2, 3
.asMap()
method on numbers
to create a map where the indices of numbers
are the keys and the corresponding elements are the values.void main() {
List<int> numbers = [1, 2, 3];
Map<int, int> map = numbers.asMap();
print('Map from numbers: $map'); // Output: Map from numbers: {0: 1, 1: 2, 2: 3}
}
Map from numbers: {0: 1, 1: 2, 2: 3}
In this example,
characters
containing the characters 'a', 'b', 'c'
.asMap()
method on characters
to create a map where the indices of characters
are the keys and the corresponding elements are the values.void main() {
List<String> characters = ['a', 'b', 'c'];
Map<int, String> map = characters.asMap();
print('Map from characters: $map'); // Output: Map from characters: {0: a, 1: b, 2: c}
}
Map from characters: {0: a, 1: b, 2: c}
In this example,
fruits
containing the strings 'apple', 'banana', 'cherry'
.asMap()
method on fruits
to create a map where the indices of fruits
are the keys and the corresponding elements are the values.void main() {
List<String> fruits = ['apple', 'banana', 'cherry'];
Map<int, String> map = fruits.asMap();
print('Map from fruits: $map'); // Output: Map from fruits: {0: apple, 1: banana, 2: cherry}
}
Map from fruits: {0: apple, 1: banana, 2: cherry}
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.