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
numberscontaining the integers1, 2, 3. - We apply the
asMap()method onnumbersto create a map where the indices ofnumbersare 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
characterscontaining the characters'a', 'b', 'c'. - We apply the
asMap()method oncharactersto create a map where the indices ofcharactersare 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
fruitscontaining the strings'apple', 'banana', 'cherry'. - We apply the
asMap()method onfruitsto create a map where the indices offruitsare 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.