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