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,
- We create a list named
numbers
containing the integers1, 2, 3
. - We apply the
asMap()
method onnumbers
to create a map where the indices ofnumbers
are the keys and the corresponding elements are the values. - The resulting map is printed to standard output.
Dart Program
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}
}
Output
Map from numbers: {0: 1, 1: 2, 2: 3}
2 Create a map from a list of characters
In this example,
- We create a list named
characters
containing the characters'a', 'b', 'c'
. - We apply the
asMap()
method oncharacters
to create a map where the indices ofcharacters
are the keys and the corresponding elements are the values. - The resulting map is printed to standard output.
Dart Program
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}
}
Output
Map from characters: {0: a, 1: b, 2: c}
3 Create a map from a list of strings
In this example,
- We create a list named
fruits
containing the strings'apple', 'banana', 'cherry'
. - We apply the
asMap()
method onfruits
to create a map where the indices offruits
are the keys and the corresponding elements are the values. - The resulting map is printed to standard output.
Dart Program
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}
}
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.