flutter 如何按值对列表中的Map进行排序

68bkxrlz  于 2022-12-24  发布在  Flutter
关注(0)|答案(1)|浏览(280)

我试着按他的名字来排序这个球员列表,但是没有用

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},
// ];

我已经尝试使用Map.fromEntries,但效果不太好

lp0sw83n

lp0sw83n1#

试试这个:

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);
 }

相关问题