简体   繁体   English

在 Flutter 中按类型排序列表和排序

[英]Sort list and order by type in Flutter

I have the following list structure for example:例如,我有以下列表结构:

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

How to sort the list in flutter in the following order, I want to see RESULT items first followed by GAME and then followed by OTHER items.如何按以下顺序对 flutter 中的列表进行排序,我想先查看 RESULT 项,然后是 GAME,然后是 OTHER 项。

Any one who have an idea for a solution?任何有解决方案的想法的人?

In your case with a List<Map<String, String>> , you should implement your own compare function.在您使用List<Map<String, String>>的情况下,您应该实现自己的比较 function。

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

You will have to add logic to your compare function, if you add new distinct type Strings.如果添加新的不同类型字符串,则必须为比较 function 添加逻辑。 Put this code in your test file and it will print:将此代码放入您的测试文件中,它将打印:

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

From the comparable docs.来自可比较的文档。

/**
 * 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM