skip to Main Content

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

3

Answers


  1. 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);
    
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
  3. 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] };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search