flutter 按降序对同时包含数字键和字母键的Map进行 dart 排序

vhmi4jdf  于 2023-01-14  发布在  Flutter
关注(0)|答案(1)|浏览(147)

我有下面的Map

Map<String, String> Dictionary = {
    '37': 'thirty-four',
    '94': 'ninety',
    '91': 'ninety-one',
    '22': 'twenty-one',
    '61': 'sixty-one',
    '9': 'nine',
    '3': 'three',
    '8': 'eight',
    '80': 'eighty',
    '81': 'eighty-one',
    'Ninety-eight': '98',
    'nine-hundred': '900'};

我想按升序排序,这样最终结果是

3: three
8: eight
9: nine
22: twenty-two
37: thirty-seven
61: sixty-one
80: eighty
81: eighty-one
91: ninety-one
94: ninety four
Ninety-eight': 98
nine-hundred': 900

但是我得到的结果是

22: twenty-two
3: three
37: thirty-seven
61: sixty-one
8: eight
80: eighty
81: eighty-one
9: nine
91: ninety-one
94: ninety-four
Ninety-eight: 98
nine-hundred: 900

以上结果的代码如下

sortDict(){

    var sortedByKeyMap = Map.fromEntries(
        Dictionary.entries.toList()..sort((e1, e2) => (e1.key).compareTo((e2.key))));

    print(sortedByKeyMap);

  }

你知道如何先将数字字符串键转换为int吗?

ewm0tg9j

ewm0tg9j1#

一个小技巧会帮到你,

var sortedByKeyMap = Map.fromEntries(
        Dictionary.entries.toList()
     ..sort((e1,e2) {
       var key1 = int.tryParse(e1.key);
       var key2 = int.tryParse(e2.key);
       return (key1 != null && key2 != null) ? key1.compareTo(key2) : e1.key.compareTo(e2.key);
     })); 
     
    print(sortedByKeyMap);

输出:

{
   "3":"three",
   "8":"eight",
   "9":"nine",
   "22":"twenty-one",
   "37":"thirty-four",
   "61":"sixty-one",
   "80":"eighty",
   "81":"eighty-one",
   "91":"ninety-one",
   "94":"ninety",
   "Ninety-eight":98,
   "nine-hundred":900
}

相关问题