Home > Mobile >  Flutter convert a list of maps into a single map
Flutter convert a list of maps into a single map

Time:01-14

I have a list of maps in flutter with each map having only 2 keys. I would like convert them into a single map where the first key is a key and the second key becomes the value.

This is the list of maps

List results = [[
  { key: shortcuts_cart_createCart, value: 0 },
  { key: shortcuts_cart_discountCartTotal, value: 0 },
  { key: shortcuts_selling_cart, value: 0 },
]

I would like to convert the list to this map

Map shorts = {
      shortcuts_selling_cart : 0,
      shortcuts_cart_createCart : 0,
      shortcuts_cart_discountCartTotal : 0
}

How do I achieve that

CodePudding user response:

you can try this

 List results = [
{ "key": "shortcuts_cart_createCart", "value": 0 },
{ "key": "shortcuts_cart_discountCartTotal", "value": 0 },
{ "key": "shortcuts_selling_cart", "value": 0 },
];

var map={};

 results.forEach((element){
map[element["key"]]=element["value"];
 });

 print(map);

CodePudding user response:

You can use Map.fromIterable and do it by one line:

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

but romIterable has very weak typing. So collection-for is the only recommended way which is:

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

CodePudding user response:

I'd use MapEntry.

Map.fromEntries(results.map(
  (innerMap) => MapEntry(innerMap['key'], innerMap['value']),
));

Also note that your code is not syntactically valid. In Dart, you have to always quote strings, even if they are keys in a map, check the documentation.

  • Related