Trier une liste personnalisée Flutter
someObjects.sort((a, b) => a.someProperty.compareTo(b.someProperty));
Worthy Warrior
someObjects.sort((a, b) => a.someProperty.compareTo(b.someProperty));
someObjects.sort();
// By object property value
someObjects.sort((a, b) => a.someProperty.compareTo(b.someProperty));
// To reverse sort, just swab a and b
someObjects.sort((a, b) => b.someProperty.compareTo(a.someProperty));
List<int> nums = [13, 2, -11];
nums.sort();
print(nums); // [-11, 2, 13]
class _Person {
final int age;
final String name;
_Person({required this.age, required this.name});
}
void _test() {
final array = [
_Person(age: 10, name: 'Dean'),
_Person(age: 20, name: 'Jack'),
_Person(age: 30, name: 'Ben'),
];
// ascend with age
// Dean Jack Ben
array.sort((p1, p2) {
return Comparable.compare(p1.age, p2.age);
});
// decend with age
// Ben Jack Dean
array.sort((p1, p2) {
return Comparable.compare(p2.age, p1.age);
});
// ascend with name
// Ben Dean Jack
array.sort((p1, p2) {
return Comparable.compare(p1.name, p2.name);
});
}