how to sort list by `enum` in Dart?

Viewed 1816

How to sort a List<Object> by enum variable in the Object in dart?

class Task {
final String name;
final Priority priority;
}

enum Priority {
first,
second,
third
}

List<Task> tasks; // <-- how to sort this list by its [Priority]?
1 Answers

Try this:

class Task {
  final String name;
  final Priority priority;
  Task(this.name, this.priority);
  @override toString() => "Task($name, $priority)";
}

enum Priority {
  first,
  second,
  third
}

extension on Priority {
  int compareTo(Priority other) =>this.index.compareTo(other.index);
}

List<Task> tasks = [
  Task('zort', Priority.second),
  Task('foo', Priority.first),
  Task('bar', Priority.third),
];

main() {
  tasks.sort((a, b) => a.priority.compareTo(b.priority));
  print(tasks);
}

It assumes your enum is declared in the correct order for sorting.

Related