Dart .asMap()
Published Mar 6, 2024
Contribute to Docs
In Dart, the .asMap() method is used to return an unmodifiable map view of a list where the keys are the indices and the values are the elements at those indices. This method is particularly useful when there is a need to work with list elements in a map-line manner, accessing them by their indices.
Syntax
newList.asMap()
newList: The name of the list on which the.asMap()method is called.
Example
In this example, the .asMap() method is used to convert a list called names into a map:
void main() {List<String> names = ['Steve', 'Tonny', 'Jack', 'Jamie'];print('Original List: $names');// Converting the list into a mapMap<int, String> nameMap = names.asMap();print('Map view of the list: $nameMap');}
Here is the output for the above example:
Original List: [Steve, Tonny, Jack, Jamie]Map view of the list: {0: Steve, 1: Tonny, 2: Jack, 3: Jamie}
Note: The resulting map remains immutable.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Dart on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours