Home > OS >  How add Map in List data - dart
How add Map in List data - dart

Time:12-20

I want to looping data in name and nation list to playerList, so i can get data in Expect Result

void main() {
  var name = ["Messi", "Ronaldo"];
  var nation = ["Argentina", "Portugal"];
  var playerList = [];
  Map<dynamic, dynamic> playerSingle = {};

  for (var i in name) {
    playerSingle['name'] = i;
    for (var j in nation) {
      playerSingle['nation'] = j;
    }
    playerList.add(playerSingle);
  }
  print(playerList);
}

// Expect Result
// [{name: Messi, nation: Argentina}, {name: Ronaldo, nation: Portugal}]

// Reality
// [{name: Ronaldo, nation: Portugal}, {name: Ronaldo, nation: Portugal}]

i tried to nested looping it but it didnt work

CodePudding user response:

You use for loop like

var name = ["Messi", "Ronaldo"];
var nation = ["Argentina", "Portugal"];
var playerList = [];
Map<dynamic, dynamic> playerSingle = {};

for (int i = 0; i < name.length; i  ) {
  playerList.add({"name": name[i] ,"nation": "${nation[i]}"});
}
print(playerList);
});

CodePudding user response:

One of the easiest way to do so is that

Map.fromIterables(name, nation);
  • Related