I want to sort a list based on a boolean using Comparable in dart. I tried the following but was not able to do it.
In the list, all the elements which are true should come first rest of the list should remain as it is.
class Item implements Comparable<Item> {
int id;
String name;
int price;
bool isAvailable;
Item({this.id, this.name, this.price, this.isAvailable = false});
@override
int compareTo(Item other) {
if (isAvailable) {
return -1;
}
return 0;
}
}
void main() {
Item item = new Item(id: 1, name: "Item one", price: 1000);
Item item2 = new Item(id: 2, name: "Item two", price: 2000);
Item item3 =
new Item(id: 3, name: "Item three", price: 500, isAvailable: true);
List<Item> items = [item, item2, item3];
items.sort();
items.forEach((Item item) {
print('${item.id} - ${item.name} - ${item.price}');
});
}
This should print
3 - Item three - 500
1 - Item one - 1000
2 - Item two - 2000
3 - Item three - 500 should come first because it is true but it is printing
1 - Item one - 1000
2 - Item two - 2000
3 - Item three - 500
What am I doing wrong?
This code can be run as it is on Dartpad here
A compareTo implementation should be reflexive, anti-symmetric, and transitive. Violating these properties can give sort results that are not self-consistent.
As written, your compareTo claims that two elements are always considered "equal" in sort order if this.isAvailable is false. But what about if other.isAvailable is true?
Your sort should work if you implement compareTo properly without trying to take shortcuts:
int compareTo(Item other) {
if (isAvailable == other.isAvailable) {
return 0;
} else if (isAvailable) {
return -1;
}
return 1;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With