I have a List of CustomObjects that I need to sort. First the objects should be sorted after their property dateTime and if that is the same, it should be sorted after another property, the compare-property.
I searched for multisort and found this:
medcimentNotificationListData.sort((med1, med2) {
var r = med1.datetime.compareTo(med2.datetime);
if (r != 0) return r;
return med1.mealTimeDescription.compareValue
.compareTo(med2.mealTimeDescription.compareValue);
});
But when printing the list right after it, the list is not sorted..
medcimentNotificationListData.forEach((medicamentNotificationData) {
print(
'${medicamentNotificationData.title}, order: ${medicamentNotificationData.mealTimeDescription.compareValue}');
});
What am I missing here? Is there an easy way to multisort?
Let me know if you need any more info!
when you are calling the
sort()method the function calls(a, b) { // your function}which should return either -1 , 0 or 1 . this function is called on the existing order. at first your elementais your first element and elementbis second element of the list as the existing order of the listif your function returns -1 it means your element
ashould be placed before the elementbtherefore it placesabefore theband call the function again by replacing older elementbas new elementaand new elementbwill be the element after the oldbelement.if your function returns 0 it means elements
aandbare both same. therefore it placesabefore theband call the function again by replacing older elementbas new elementa.but when your function returns the 1 it means your element
ais coming after the elementb. therefore the function is called again by replacing elementawith the element before the old elementa.Following code shows how this is works
output