0

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

1
  • Can you tell us the logic behind Welt will come first then blid then vimn then drit Commented Apr 5, 2022 at 10:27

2 Answers 2

3

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]
}
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.