D
BLoC PatternMedium30 XP3 min read

Why use sealed classes for Bloc states?

TL;DR: Sealed classes (Dart 3.0+) make state unions exhaustive. The compiler forces you to handle every subclass in a switch expression — you can't accidentally forget the error or loading state.

Full Answer

Before sealed classes, Bloc states were often modeled as abstract classes with subclasses. The risk: forgetting to handle a state in the UI causes silent bugs.

Sealed classes add compile-time exhaustiveness checking to switch expressions. If you add a new state subclass, every switch that doesn't handle it becomes a compile error.

🎯

Combine sealed classes with the Freezed package for immutable states with copyWith(), == overrides, and JSON serialization.

Code Examples

dartSealed class state with exhaustive switch
Output
// Compiler error if any state is unhandled
// Destructuring: QuizLoaded(:final questions) — direct access

Common Mistakes

  • Using abstract class + if-else chain instead of sealed + switch — no exhaustiveness check
  • Not using const constructors for terminal states like QuizInitial and QuizLoading

Interview Tip

💡

Sealed classes + switch expressions = compile-time complete state coverage. Mention that this is the Dart equivalent of Kotlin's sealed classes or Rust's enums.

#sealed-class#state-modeling#exhaustive-switch#union-type