I want to sort a personArray
with age
and name
:
final personArray = [
_Person(age: 10, name: 'Dean'),
_Person(age: 20, name: 'Jack'),
_Person(age: 30, name: 'Ben'),
_Person(age: 30, name: 'Alice'),
];
personArray.sort((p1, p2) {
return Comparable.compare(p1.age, p2.age);
});
for (final element in personArray) {
print(element.name);
}
Console print: Dean Jack Ben Alice.
But what I want is: Dean Jack Alice Ben.
The pseudocode looks like:
personArray.sort((p1, p2) {
return Comparable.compare(p1.age, p2.age) && Comparable.compare(p1.name, p2.name);
});
Anyway can do it?
2
Answers
Change your compare function
you can try this code
it will sort the objects with respect to name.
and this will sort it first with age and if both the age are equal then it will sort the objects with respect to name.