Home > database >  How to sort Map in List by Value
How to sort Map in List by Value

Time:12-23

I am trying to sort this player list by his name, but it didn't work

var player = [
  {"name": "Ronaldo", "nation": "Portugal", "age": 30},
  {"name": "Messi", "nation": "Argentina", "age": 30},
  {"name": "Dibala", "nation": "Portugal", "age": 30},
  {"name": "Maria", "nation": "Argentina", "age": 30},
  {"name": "Alves Dani", "nation": "Portugal", "age": 30},
];

var sortedAscending = [];

void main(List<String> args) {
  for (var item in player) {
    final sorted = Map.fromEntries(
        item.entries.toList()..sort((e1, e2) => e1.key.compareTo(e2.key)));
    print(sorted);
    sortedAscending.add(sorted);
  }
  print(sortedAscending);
}

// Expect Result
// [
//   {"name": "Alves Dani", "nation": "Portugal", "age": 30},
//   {"name": "Dibala", "nation": "Portugal", "age": 30},
//   {"name": "Maria", "nation": "Argentina", "age": 30},
//   {"name": "Messi", "nation": "Argentina", "age": 30},
//   {"name": "Ronaldo", "nation": "Portugal", "age": 30},
// ];

I already try using Map.fromEntries but it didn't go well

CodePudding user response:

Try this:

var player = [
      {"name": "Ronaldo", "nation": "Portugal", "age": 30},
      {"name": "Messi", "nation": "Argentina", "age": 30},
      {"name": "Dibala", "nation": "Portugal", "age": 30},
      {"name": "Maria", "nation": "Argentina", "age": 30},
      {"name": "Alves Dani", "nation": "Portugal", "age": 30},
    ];

 void sort(){

    player.sort((e1, e2) => e1['name'].toString().compareTo(e2['name'].toString()));

    print(player);
 }
  • Related