Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.
I tried it like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  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

>Solution :

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading