【问题标题】:Sort list and order by type in Flutter在 Flutter 中按类型排序列表和排序
【发布时间】:2020-03-16 15:27:49
【问题描述】:

例如,我有以下列表结构:

{
    'name': 'Item001',
    'type': 'RESULT'
},{
    'name': 'Item002',
    'type': 'OTHER'
},
{
    'name': 'Item005',
    'type': 'GAME'
},
{
    'name': 'Item0039',
    'type': 'RESULT'
}

如何按以下顺序对列表进行排序,我想先查看 RESULT 项,然后是 GAME,然后是 OTHER 项。

任何人有解决方案的想法?

【问题讨论】:

    标签: list sorting flutter


    【解决方案1】:

    在您使用List<Map<String, String>> 的情况下,您应该实现自己的比较函数。

    void main() {
      final list = [
        {'name': 'Item001', 'type': 'RESULT'},
        {'name': 'Item002', 'type': 'OTHER'},
        {'name': 'Item005', 'type': 'GAME'},
        {'name': 'Item0039', 'type': 'RESULT'},
      ];
    
      int _compare(Map<String, String> map1, Map<String, String> map2) {
        var compare;
        if (map1['type'] == map2['type'])
          compare = 0;
        else if (map1['type'] == 'RESULT' && map2['type'] == 'GAME')
          compare = -2;
        else if (map1['type'] == 'RESULT' && map2['type'] == 'OTHER')
          compare = -1;
        else if (map1['type'] == 'GAME' && map2['type'] == 'OTHER')
          compare = -1;
        else
          compare = 1;
        return compare;
      }
    
      test('sorting_this_list', () {
        list.sort(_compare);
    
        print('\n');
        list.forEach(print);
      });
    }
    

    如果您添加新的不同类型字符串,则必须向比较函数添加逻辑。将此代码放入您的测试文件中,它将打印:

    {name: Item001, type: RESULT}
    {name: Item0039, type: RESULT}
    {name: Item005, type: GAME}
    {name: Item002, type: OTHER}
    

    来自可比较的文档。

    /**
     * The signature of a generic comparison function.
     *
     * A comparison function represents an ordering on a type of objects.
     * A total ordering on a type means that for two values, either they
     * are equal or one is greater than the other (and the latter must then be
     * smaller than the former).
     *
     * A [Comparator] function represents such a total ordering by returning
     *
     * * a negative integer if [a] is smaller than [b],
     * * zero if [a] is equal to [b], and
     * * a positive integer if [a] is greater than [b].
     */
    typedef Comparator<T> = int Function(T a, T b);
    

    【讨论】:

      猜你喜欢
      • 2021-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-21
      相关资源
      最近更新 更多