D
Dart LanguageAdvanced50 XP5 min read

What are sealed classes in Dart 3 and how do they enable exhaustive matching?

TL;DR: Sealed classes restrict which classes can extend them (only within the same library). This gives the compiler a complete list of subtypes, enabling exhaustiveness checking in switch statements — like Kotlin sealed classes or Rust enums.

Full Answer

When you switch on a sealed type, Dart's compiler verifies every subtype is handled. If you add a new subtype, all switches that don't handle it produce compile errors — preventing missed cases at runtime.

🎯

BLoC states and Riverpod async states map perfectly to sealed classes. flutter_bloc's Emittable is now typically modeled as sealed classes in Dart 3 apps.

Code Examples

dartSealed class for network state
Output
Returns appropriate widget for each network state.
Compiler error if any NetworkState subtype is not handled.

Interview Tip

💡

Sealed classes replace the need for abstract classes + runtime type checking. The exhaustiveness guarantee means bugs from missing cases are caught at compile time, not in production.

#sealed#exhaustive#pattern-matching#dart-3#union-types