Sub topic 10
Sealed Unions for Multiple States
This chapter assumes you know Dart classes, named parameters, null safety, and basic Flutter state handling. It also assumes you can run code generation with build_runner.
A screen often has several valid states. For example, a request can be loading, successful, or failed. A nullable data field plus an error string can represent these states, but it also allows invalid combinations, such as showing an error while claiming that data is ready.
A sealed union models the alternatives directly. A union is one type with several named constructors. Each constructor represents a different variant and can carry data specific to that variant. A sealed class restricts which variants can exist, so Dart can check that pattern matching handles every case.
Declaring the state
Freezed generates the implementations for the constructors and their value behavior:
import 'package:freezed_annotation/freezed_annotation.dart';
part 'load_state.freezed.dart';
@freezed
sealed class LoadState with _$LoadState {
const factory LoadState.loading() = LoadStateLoading;
const factory LoadState.data(List<String> items) = LoadStateData;
const factory LoadState.error(String message) = LoadStateError;
}This declaration creates one public type, LoadState, with three variants:
| Variant | Data | Meaning |
|---|---|---|
| LoadStateLoading | None | The request is still running |
| LoadStateData | A list of strings | The request completed successfully |
| LoadStateError | An error message | The request failed |
Run build_runner after creating or changing the declaration:
dart run build_runner build --delete-conflicting-outputsThe generated file contains the concrete classes and members needed by the union. Do not edit that file manually.
Handling every variant
Dart 3 switch expressions work well with sealed Freezed unions. The compiler can warn when a new constructor is added but not handled:
String describe(LoadState state) => switch (state) {
LoadStateLoading() => 'Loading',
LoadStateData(:final items) => '${items.length} items',
LoadStateError(:final message) => 'Error: $message',
};The pattern LoadStateData(:final items) extracts the items field into a local variable. The error pattern extracts message in the same way.
A traditional switch statement can also match the variants, but a switch expression is useful when each state produces one value, such as a label, widget, or navigation decision.
Modeling Flutter UI state
A widget or state-management layer can map each variant to a different interface:
String messageFor(LoadState state) => switch (state) {
LoadStateLoading() => 'Fetching items...',
LoadStateData(:final items) =>
items.isEmpty ? 'No items found' : 'Found ${items.length} items',
LoadStateError(:final message) => message,
};Each state carries only the information it needs. Loading does not need a meaningless list. Error does not need nullable success data.
Common errors include forgetting the generated part file, using a variant name that does not match its constructor, and treating a union like an enum. An enum names fixed values but cannot naturally carry different fields for each value. A union is better when each state has different data.
Exercise
Why is LoadStateError(String message) usually safer than a single LoadState class with nullable data and nullable error fields?
Show answer
The union prevents invalid combinations by making loading, success, and failure separate variants with their own fields.