How do enhanced enums work in Dart 3 and what patterns do they enable?
TL;DR: Dart 2.17+ enums can have fields, methods, constructors, and implement interfaces. Dart 3 sealed classes + pattern matching let you model exhaustive state machines. Use enums for fixed sets of values with behavior; sealed classes for polymorphic variants.
Full Answer
Enhanced Enums (Dart 2.17+)
Enums can now have: constructor with final fields, instance methods, getters, and implement interfaces. This makes them much more powerful for modeling domain concepts.
Sealed Classes (Dart 3)
sealed class creates an exhaustive hierarchy. The compiler verifies that switch expressions cover all subclasses. Perfect for BLoC states, Result types, and network responses.
sealed class + switch expression = compile-time exhaustiveness checking. Adding a new subclass breaks all unhandled switches โ you can't forget to handle new states.
Code Examples
true Not Found Loading...
Common Mistakes
- โUsing if/else chains instead of switch expressions on sealed classes โ misses exhaustiveness checking
- โUsing enums when the set of values can grow at runtime โ enums are compile-time constants only
Interview Tip
Dart 3 sealed classes replace the need for freezed in many BLoC use cases. Show that switch expressions on sealed classes are exhaustive โ the compiler catches missing cases.