{

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. Convert List to Map or Map to List in Dart and flutter

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 a 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 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.asMap();// {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 toList() method on returned keys and values to convert to List type.

map.keys.toList(): converts keys into List of keys

map.keys.toList(): method converts keys int List of values

Here is an example program to convert map key 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.

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.





Related posts

Dart| Flutter How to: Read pubspec.yaml attributes (version) with examples

How to Create and build a Singleton Class Dart or Flutter example| Dart By Example

What is the difference between var and dynamic and final in dart?| Flutter By Example

How to: Check if Phone number is valid or not in Dart| Flutter By Example

Dart| Flutter How to read an image from a disk and resize a file

Dart/Flutter: How to write setter and getter fields or members variables in a class with Example

Dart| Flutter How to get extension name and MIME type of a file with example