Skip to content

Instantly share code, notes, and snippets.

@DFreds
Created November 13, 2019 14:28
Show Gist options
  • Select an option

  • Save DFreds/17db0c3f8165839b7202a8ce63e5e7df to your computer and use it in GitHub Desktop.

Select an option

Save DFreds/17db0c3f8165839b7202a8ce63e5e7df to your computer and use it in GitHub Desktop.
Sorting in Dart by Comparable
void main() {
List<Person> list = [
Person(name: "Peter", age: 25),
Person(name: "Peter", age: 22),
Person(name: "John", age: 26),
Person(name: "Max", age: 26)
];
print("Unsorted: $list");
list.sort((Person personA, Person personB) => personA.compareTo(personB));
print("Sorted: $list");
}
class Person implements Comparable<Person> {
final String name;
final int age;
Person({this.name, this.age});
@override
String toString() {
return "Name: $name - $age";
}
@override
int compareTo(Person other) {
if (this.name.compareTo(other.name) == -1) {
return -1;
}
if (this.name.compareTo(other.name) == 0) {
if (this.age < other.age) return -1;
else if (this.age == other.age) return 0;
else return 1;
}
return 1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment