Different Ways to Convert a List to Map Dart | Flutter

Created At: 2022-04-04 13:13:47 Updated At: 2022-04-04 13:53:56

There are a few different ways to convert from a List to Map in Dart.

First way using asMap()

Let's say we have a list like below

List list = ['steve', 'bill', 'musk'];

If we want to conver it to a list, then we call the below method on the list object

Map map = list.asMap();
print(map);

Calling asMap() method on the list object would convert it to a map. And it will print below like

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

With this approach you convert a list to a map, but we don't have control on this map, since we won't be able to edit this.

 

Second way using for loop

The list we have seen above, we can covert to a map in a different way, using for loop.

List list = ['steve', 'bill', 'musk'];

Map map = { for (var item in list)   '$item':'valuesOf$item' };

print(map);

And the result would be 

{steve: valuesOfsteve, bill: valuesOfbill, musk: valuesOfmusk}

With this approach you can modify the keys or values as you convert or generate it to a map.

for example, we can introduce a new variable x at the top, and insert it within curly braces with key or value.

List list = ['steve', 'bill', 'musk'];

int x=0;
  
Map map = { for (var item in list) x++ : '$item' };

print(map);

Now this would output the same as the first method

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

You can also make side changes with x++ and '$item'. 

List list = ['steve', 'bill', 'musk'];

int x=0;
  
Map map = { for (var item in list)  '$item':x++ };

print(map);

You see, in the above code now we have moved '$item' to the left and x++ to the right. and the output is

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

 

Third way using fromIterable()

We use Map.fromIterable() contstructor to generate or convert a list to a map.

List list = ['steve', 'bill', 'musk'];

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

print(result);

and the result is

{s: t, b: i, m: u}

With the output you can see that, may need to change the indiex as per your need when you convert a list to a map.

Change the index here to access a different key and value

 (v) => v[0], value: (v) => v[1]

 

Comment

Add Reviews