Reputation: 2791
How do you sort a List
in dart based on a bool
value, the compareTo
method doesn't work with bool
. I want true
values to appear at the top of the list.
Upvotes: 24
Views: 17180
Reputation: 51
For List<bool>
, you need to define a compare function:
final boollist = <bool>[false, true, true, false];
boollist.sort(
(a, b) => (a == b ? 0 : (a ? 1 : -1)),
);
output:
[false, false, true, true]
The reasons for this situation with bool
in Dart can be read here.
Upvotes: 5
Reputation: 9
I just got the same issue, I solve it using the .toString() function. So it's sort separating the 0's to the 1's.
In this case I got a list of forms, some are synced and others no.
Here's my code:
final forms = state.forms
..sort(
(a, b) => a.synced.toString().compareTo(b.synced.toString()),
);
Hope it works for you.
Upvotes: -1
Reputation: 17141
You can define your own compare function for bool
and pass it to the sort
method of List
.
Example with booleans
as your bool
List
:
booleans.sort((a, b) {
if(b) {
return 1;
}
return -1;
});
This example tells the sort
method that true
elements should be sorted higher than false
elements.
Upvotes: 49