Skip to content

Enum .sort() Throws an Error Unless Explicit Comparator is ProvidedΒ #60135

@bgoncharuck

Description

@bgoncharuck

Enum .sort() Throws an Error Unless Explicit Comparator is Provided

Description

I encountered an inconsistency when sorting a list of enums in Dart. Calling .sort() directly on a List<Enum> throws an error, but providing an explicit comparator using .index.compareTo() works as expected.

Steps to Reproduce

enum SortableType { A, B, C }

void main() {
  var list1 = SortableType.values.toList();
  var list2 = SortableType.values.toList();

  list1.sort(); // Throws an error
  list2.sort((a, b) => a.index.compareTo(b.index)); // Works fine
}

Expected Behavior

  • Since sorting an enum by its index is the most logical behavior, list1.sort(); should work without requiring a custom comparator.

Actual Behavior

  • list1.sort(); throws an error.
  • list2.sort((a, b) => a.index.compareTo(b.index)); works fine.

Proposal

Would it make sense for Enum to implement Comparable by default using its index?

Environment Details

Any.
Dartpad: https://dartpad.dev/

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions