简体   繁体   English

自定义排序 flutter 中的字符串列表

[英]custom sort a string list in flutter

I have a list (in flutter):我有一个列表(颤动):

loadedSummaryList = [
         'BILD',
         'DRIT',
         'VIMN',
         'WELT',
         'FLUTTER',
         'ALL'
       ];

, and I want to sort this list like: ,我想像这样对这个列表进行排序:

['WELT', 'BILD', 'VIMN', 'DRIT', 'ALL', 'FLUTTER']

in other words, I want to sort the first four elements of the list always like 'WELT', 'BILD', 'VIMN', 'DRIT', and then alphabetically.换句话说,我想对列表的前四个元素进行排序,例如“WELT”、“BILD”、“VIMN”、“DRIT”,然后按字母顺序排序。 I tried it like this:我这样试过:

  List<String> sortList = ['WELT', 'BILD', 'VIMN', 'DRIT'];
       
  loadedSummaryList.sort(
          (a, b) {
            int aIntex = sortList.indexOf(a.name);
            int bIntex = sortList.indexOf(b.name);
            return aIntex.compareTo(bIntex);
          },
        );

which returns返回

['ALL', 'FLUTTER', 'WELT', 'BILD', 'VIMN', 'DRIT'];

but actually, I want to have it like:但实际上,我想让它像:

['WELT', 'BILD', 'VIMN', 'DRIT', 'ALL', 'FLUTTER']

could someone help me, please?有人可以帮我吗? thanks in advance提前致谢

Just sort them and merge them into one.只需对它们进行排序并将它们合并为一个即可。

void main() {
  var all = <String>['BILD', 'DRIT', 'VIMN', 'WELT', 'FLUTTER', 'ALL'];
  var sort = <String>['WELT', 'BILD', 'VIMN', 'DRIT'];
  
  // It depends on how you want list sorting in the end result.
  // You can sort both lists if you want.
  all.sort();
  //sort.sort(); 
  
  var result = sort.followedBy(all).toSet().toList();
  
  print(result); // [WELT, BILD, VIMN, DRIT, ALL, FLUTTER]
}

First thing, indexOf returns -1 when the element is not in the list, therefore it will put those in front.首先,当元素不在列表中时, indexOf返回-1 ,因此它将把那些放在前面。 A solution for that is to change it to a higher number in that case.解决方案是在这种情况下将其更改为更高的数字。 Secondly, you also need to sort them alphabetically, which you don't do now.其次,您还需要按字母顺序对它们进行排序,而您现在不需要这样做。 You can do that by doing a compareTo on the strings themselves in the case that the first compareTo returns 0 .在第一个compareTo返回0的情况下,您可以通过对字符串本身执行compareTo来做到这一点。

final result:最后结果:

loadedSummaryList.sort(
      (a, b) {
    int aIntex = sortList.indexOf(a);
    int bIntex = sortList.indexOf(b);
    if (aIntex == -1) aIntex = sortList.length;
    if (bIntex == -1) bIntex = sortList.length;
    var result = aIntex.compareTo(bIntex);
    if (result != 0) {
      return result;
    } else {
      return a.compareTo(b);
    }
  },
);

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

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