Home > Back-end >  custom sort a string list in flutter
custom sort a string list in flutter

Time:04-05

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. 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

CodePudding user response:

First thing, indexOf returns -1 when the element is not in the list, therefore it will put those in front. 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.

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

CodePudding user response:

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]
}
  • Related