D
OOP & SOLIDMedium30 XP4 min read

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

dartEnhanced enum and sealed class
Output
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.

#enum#dart3#sealed-class#pattern-matching