How to convert List to Map or vice-versa in Dart| Flutter By Example
This tutorial shows multiple ways to convert List to Map in Dart or flutter programming.
The List is a dynamic collection of objects in Dart. The map is a data structure to store key and value pairs.
Both are different types in Dart or Flutter, and We have to write code to convert from one type into another.
How to convert List to Map in Dart or Flutter programming
List.asMap() method converts a list into a map type with indexed keys. And the returned map is unmodified and non-editable.
Here is an example program
main() {
List wordsList = ['one', 'two', 'three'];
Map wordsMap = wordsList.asMap();
print(wordsMap); //{0: one, 1: two, 2: three}
var numberList = [3, 6, 2, 7, 51, 15, 4];
Map numbersMap = numberList.asap();// {0: 3, 1: 6, 2: 2, 3: 7, 4: 51, 5: 4}
print(numbersMap);
}
How to convert Map to List in Dart or Flutter programming?
The map contains keys and values.
to convert to List, use toList() method. map.keys
returns keys of type Iterable<dynamic>
and map.values
returns values of type Iterable<dynamic>
. So call the toList() method on returned keys and values to convert to List type.
map.keys.toList()
: converts keys into a List of keys
map.keys.toList()
: method converts keys int List of values
Here is an example program to convert map keys and values into separate lists
main() {
List wordsList = ['one', 'two', 'three'];
Map wordsMap = wordsList.asMap();
print(wordsMap); //{0: one, 1: two, 2: three}
var keyList = wordsMap.keys.toList();
print(keyList);
var valuesList = wordsMap.values.toList();
print(valuesList);
}
Conclusion
Learn How to Convert List to Map or Map to List in Dart or flutter programming.