Sub topic 13
Choosing between sealed classes, enums, and generated unions
Assume you know Dart classes, null safety, basic generics, and Flutter’s build method. This chapter focuses on choosing a state representation after you understand exhaustive pattern matching.
Start with the shape of the state
An enum is best when the state is a small list of names and every name has the same kind of data, or no data at all.
enum ConnectionStatus { disconnected, connecting, connected }
String label(ConnectionStatus status) => switch (status) {
ConnectionStatus.disconnected => 'Offline',
ConnectionStatus.connecting => 'Connecting',
ConnectionStatus.connected => 'Online',
};
void main() {
print(label(ConnectionStatus.connected));
}This is compact and easy to serialize. However, an enum cannot make connected carry a user object while connecting carries a retry count. You must store that data somewhere else, often in nullable fields or a separate map. Those extra fields can become inconsistent with the enum value.
A sealed class is a better fit when each variant has different data or different rules.
sealed class LoadState<T> {
const LoadState();
}
final class Loading<T> extends LoadState<T> {
const Loading();
}
final class Loaded<T> extends LoadState<T> {
const Loaded(this.data);
final T data;
}
final class Failed<T> extends LoadState<T> {
const Failed(this.error);
final Object error;
}
String describe(LoadState<List<String>> state) => switch (state) {
Loading() => 'Loading',
Loaded(data: final items) => '${items.length} items',
Failed(error: final error) => 'Error: $error',
};
void main() {
print(describe(const Loaded(['A', 'B'])));
}Here, Loaded must contain data, while Loading does not. The type itself prevents invalid combinations such as a loading state with a stale error.
Compare the main choices
| Choice | Use it when | Main cost |
|---|---|---|
| `enum` | Variants are names with little or no variant-specific data | Related data needs separate storage |
| Sealed classes | Variants carry different data and have different behavior | More declarations and manual boilerplate |
| Generated unions | You want sealed-class behavior with less repetitive code | Build tooling and generated files add complexity |
A generated union is a sealed-style hierarchy produced by a tool such as Freezed. You declare the variants, and the generator creates constructors, equality, pattern-like helpers, and sometimes serialization support. This is useful for large models, immutable application state, and teams that already use code generation.
Generated code does not remove design decisions. You still need to decide whether Loading, Loaded, and Failed are the right variants. It also adds a build step, generated files, package configuration, and possible version conflicts.
Decision criteria and limits
Choose an enum when:
- The state is genuinely just a label.
- Variant-specific data is unnecessary.
- Simple JSON or database serialization matters.
Choose sealed classes when:
- Each state has different fields.
- State transitions should be checked by the compiler.
- The state logic belongs in ordinary Dart functions that are easy to unit test.
Choose generated unions when:
- The project already uses a generator.
- Models need value equality, copying, serialization, or many variants.
- Repeated manual class code would obscure the feature.
A sealed class is closed only within its library. Keep the parent and its direct subclasses in the same Dart library so exhaustiveness checking sees every variant. Also avoid using _ as a switch case too early. A wildcard makes the compiler accept future variants without forcing you to review the affected UI or transition logic.
Test the choice with transitions
Keep transition logic independent from widgets. A plain function that accepts the current state and an event can be tested without Flutter. If adding a new state causes compiler errors in this function and in the UI mapping, the type system is doing useful work.
Generated unions can provide similar guarantees, but the exact API depends on the generator. Read its documentation and check how it reports missing cases before adopting it.
Exercise
You need idle, saving, and saved states, where only saving has no data and saved contains a timestamp. Which representation should you choose, and why?
Show answer
Choose a sealed class hierarchy. The variants have different data requirements, and exhaustive switches can ensure that every state is handled.