Home > Back-end >  flutter convert two lists to one map
flutter convert two lists to one map

Time:10-19

what is the best way to convert these two Lists

    var list1 =[a, b, c]
    var list2 =[1 ,2, 3]

to this Map

Map<dynamic,dynamic> Map1 = {
      "a": 1,
      "b": 2,
      "c": 3,
    };

CodePudding user response:

There's a built-in for that:

final theMap = Map.fromIterables(list1, list2);

You should really review the protocol of the major core types (List, Map, Set, and so on) on at least a monthly basis. I still do!

CodePudding user response:

Loop over the keys and add the elements from the second list as value. The two lists should be at least the same length, otherwise you are accessing an index that does not exist.

  var list1 =["a", "b", "c"];
  var list2 =[1 ,2, 3];
  var map = {};
  for(int i = 0; i < list1.length; i  ){
    map[list1[i]] = list2[i];
  }
  print(map);
  • Related