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 element a
is your first element and element b
is second element of the list as the existing order of the list
if your function returns -1 it means your element a
should be placed before the element b
therefore it places a
before the b
and call the function again by replacing older element b
as new element a
and new element b
will be the element after the old b
element.
if your function returns 0 it means elements a
and b
are both same. therefore it places a
before the b
and call the function again by replacing older element b
as new element a
.
but when your function returns the 1 it means your element a
is coming after the element b
. therefore the function is called again by replacing element a
with the element before the old element a
.
Following code shows how this is works
final List<int> list = [1, 0, 3, 4, 2 , 6, 8, 2 , 5];
list.sort((a,b) {
print("a : $a, b : $b");
int result = a.compareTo(b);
print('result : $result \n');
return result;
});
output
a : 1, b : 0
result : 1
a : 1, b : 3
result : -1
a : 3, b : 4
result : -1
a : 4, b : 2
result : 1
a : 3, b : 2
result : 1
a : 1, b : 2
result : -1
a : 4, b : 6
result : -1
a : 6, b : 8
result : -1
a : 8, b : 2
result : 1
a : 6, b : 2
result : 1
a : 4, b : 2
result : 1
a : 3, b : 2
result : 1
a : 2, b : 2
result : 0
a : 8, b : 5
result : 1
a : 6, b : 5
result : 1
a : 4, b : 5
result : -1
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.