flutterdart

How to sort a list of objects by enum variable in the object in Dart?


I want to sort a list of Objects by an enum variable in the object in Dart?

for Example:

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

enum Priority {
first,
second,
third
}

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

Solution

  • 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.