D
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

AspectEquatableFreezed
SetupExtend Equatable, override props@freezed + build_runner
copyWithManual implementationAuto-generated
Union typesNot supported nativelyFirst-class with when()/map()
JSONNot providedfromJson/toJson with @JsonSerializable
ImmutabilityNot enforcedAll 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