BLoC PatternMedium30 XP4 min read
How do you use Freezed to model immutable Bloc states?
TL;DR: Freezed generates immutable data classes with copyWith(), == and hashCode, pattern matching (when/map), and union types. Use @freezed on your state class to get all these for free, replacing Equatable.
Full Answer
Freezed vs Equatable
| Aspect | Equatable | Freezed |
|---|---|---|
| Setup | Extend Equatable, override props | @freezed + build_runner |
| copyWith | Manual implementation | Auto-generated |
| Union types | Not supported natively | First-class with when()/map() |
| JSON | Not provided | fromJson/toJson with @JsonSerializable |
| Immutability | Not enforced | All fields are final by design |
๐ฏ
Freezed's when() is safer than sealed class switch โ it supports named parameters and exhaustive matching with a convenient fallback via orElse.
Code Examples
dartFreezed union state for quiz
Output
// Generated copyWith: change only what you need // when(): exhaustive pattern matching, compile-time safe
Common Mistakes
- โForgetting to run build_runner after changing the class โ the generated file is stale
- โUsing Freezed and Equatable together โ Freezed already generates == and hashCode
Interview Tip
๐ก
Freezed is a superset of Equatable with code generation. Mention that the flutter_bloc team recommends Freezed for complex state modeling, especially union types.
#freezed#immutable#copyWith#union#code-generation