How to convert a List into a Map in Dart

You can use Map.fromIterable:

var result = Map.fromIterable(l, key: (v) => v[0], value: (v) => v[1]);

or collection-for (starting from Dart 2.3):

var result = { for (var v in l) v[0]: v[1] };

For Dart 2.3 and more ,

There are many solutions, but the simplest are :

1- Use the asMap() function

List list = ['steve', 'bill', 'musk'];
Map map = list.asMap();
print(map);

Output :

{0: steve, 1: bill, 2: musk}

2- Use for-in collection inside your map Map map = {};

List list = ['steve', 'bill', 'musk'];
Map map = {for (var item in list) '$item' : 'valueOf$item'};
print(map);

Output :

{steve: valueOfsteve, bill: valueOfbill, musk: valueOfmusk}

Hope it will be helpful .


In Dart 1.1, you can use this constructor of Map:

new Map.fromIterable(list, key: (v) => v[0], value: (v) => v[1]);

This would be closest to your original proposal.

Tags:

List

Map

Dart