Dart sort List by two fields
Tien Nguyen
Posted on March 26, 2022
In this tutorial, we'll show you some ways and functions to sort list by two fields in Dart/Flutter
For sorting multiple fields, or two fields for this tutorial. I will also show you two ways:
- using custom compare function.
- extending
Comparable
abstract class and overridecompareTo()
method
Full post: Dart/Flutter Sort List of objects
Dart Sort list by two fields using custom compare function
We're gonna pass a more complicated custom compare function into list's sort()
method.
First we sort the list of objects by field name
, then field age
.
class Customer {
String name;
int age;
Customer(this.name, this.age);
@override
String toString() {
return '{ ${this.name}, ${this.age} }';
}
}
main() {
List<Customer> customers = [];
customers.add(Customer('Jack', 23));
customers.add(Customer('Adam', 27));
customers.add(Customer('Katherin', 25));
customers.sort((a, b) {
int nameComp = a.name.compareTo(b.name);
if (nameComp == 0) {
return -a.age.compareTo(b.age); // '-' for descending
}
return nameComp;
});
print('Sort by Name(ASC), then Age(DESC):\n' + customers.toString());
}
Output:
Sort by Name(ASC), then Age(DESC):
[{ Adam, 27 }, { Jack, 32 }, { Jack, 23 }, { Katherin, 25 }]
Dart Sort list by two fields using Comparable abstract class
The second approach is to extend Comparable
abstract class and override compareTo()
method. Now we don't need to pass compare
function, we just call list.sort()
instead of list.sort(compare)
.
class Customer extends Comparable {
String name;
int age;
Customer(this.name, this.age);
@override
String toString() {
return '{ ${this.name}, ${this.age} }';
}
// sort by Name (asc)
@override
int compareTo(other) {
return this.name.compareTo(other.name);
}
}
main() {
List<Customer> customers = [];
customers.add(Customer('Jack', 23));
customers.add(Customer('Adam', 27));
customers.add(Customer('Katherin', 25));
customers.add(Customer('Jack', 32));
customers.sort();
print('Sort by Name(ASC), then Age(DESC):\n' + customers.toString());
}
Output:
Sort by Name(ASC), then Age(DESC):
[{ Adam, 27 }, { Jack, 32 }, { Jack, 23 }, { Katherin, 25 }]
Further Reading
💖 💪 🙅 🚩
Tien Nguyen
Posted on March 26, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.