Sub topic 13
Choosing between sealed classes, enums, and generated unions
You have used sealed classes to model screen state. This chapter covers when a sealed class is the wrong tool, and when a generated union is worth its cost. It assumes you can write Dart 3 switch expressions with object patterns, and that you know how enums and part files work. For the generated option, it also assumes you have run build_runner before.
The decision in short
Three tools can model "one of several things" in Dart 3:
- An enum is a fixed set of constant values. Every value has the same shape.
- A sealed class is a closed set of subtypes. Each subtype can carry different fields.
- A generated union (for example from the
freezedpackage) is a sealed class hierarchy where a code generator writes the boilerplate: equality,copyWith,toString, and optionally JSON.
All three give you exhaustive switch. The differences are in what each variant can hold, how much code you write, and what your build needs.
Enums: same shape, no payload
Use an enum when each alternative is just a label, and any extra data is the same for every value. Dart's enhanced enums can have fields, methods, and getters, so an enum is more capable than it looks.
enum Connection {
online,
offline;
bool get canSync => switch (this) {
Connection.online => true,
Connection.offline => false,
};
}
void main() {
for (final c in Connection.values) {
print('$c canSync=${c.canSync}');
}
}Enums have two properties a sealed class lacks:
- Built-in serialization hooks.
name,index, andConnection.valuescome for free.Connection.values.byName('online')parses a stored string. - Value equality. Each enum value is a single constant instance, so
==just works.
An enum cannot give one value a field that the others lack. If offline needs a lastSeen timestamp and online does not, you have two options. You can add a nullable lastSeen to every value, which brings back the impossible states from the first chapter. Or you can switch to a sealed class. The second option is almost always right.
Sealed classes: different data per variant
Reach for a sealed class when variants differ in what they carry. Loading has nothing, Loaded has data, and Failed has an error. A sealed class lets each variant declare exactly its own fields, and the compiler rejects access to a field that does not belong to the matched variant.
Sealed classes also compose with enums. A variant can hold an enum when one part of its data is a small fixed set:
sealed class LoadState<T> {
const LoadState();
}
enum FailureReason { network, unauthorized, unknown }
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.reason);
final FailureReason reason;
}
String message(LoadState<List<String>> state) => switch (state) {
Loading() => 'Loading...',
Loaded(data: final items) => '${items.length} items',
Failed(reason: FailureReason.network) => 'Check your connection',
Failed(reason: FailureReason.unauthorized) => 'Please sign in again',
Failed(reason: FailureReason.unknown) => 'Something went wrong',
};The nested enum patterns are checked too. If you add FailureReason.timeout, the switch above stops compiling until you handle it. Putting the small closed set in an enum, and the structural difference in the sealed class, avoids creating one subclass per failure reason.
What you write by hand
Sealed class subtypes do not get value equality. Two Loaded(['a']) objects are different unless you override ==:
final class Loaded<T> extends LoadState<T> {
const Loaded(this.data);
final T data;
@override
bool operator ==(Object other) =>
other is Loaded<T> && other.data == data;
@override
int get hashCode => Object.hash(Loaded, data);
}This matters because many state management setups compare the old and new state to decide whether to rebuild. Without ==, every emission looks like a change. With it, note that data == data on two List objects compares identity, not contents. If T is a list, you need a deep equality helper such as listEquals from package:flutter/foundation.dart, or you must make sure you emit new lists only when the contents change.
Writing ==, hashCode, toString, and copyWith for every variant is the main cost of a hand-written hierarchy. For three small states, the cost is low. For fifteen states with six fields each, it is not.
Generated unions: boilerplate removed, build step added
A generated union moves the boilerplate to a code generator. With freezed version 3, the same state looks like this:
import 'package:freezed_annotation/freezed_annotation.dart';
part 'load_state.freezed.dart';
@freezed
sealed class LoadState<T> with _$LoadState<T> {
const factory LoadState.loading() = Loading<T>;
const factory LoadState.loaded(T data) = Loaded<T>;
const factory LoadState.failed(Object error) = Failed<T>;
}You then run dart run build_runner build. The generator writes load_state.freezed.dart with the Loading, Loaded, and Failed classes, including ==, hashCode, toString, and copyWith. The result is still a Dart 3 sealed class, so the switch expressions from earlier chapters work on it without change.
What you gain
- Value equality and
copyWithon every variant, with no hand-written code. - Optional JSON support through
json_serializablewhen state must be saved or sent. - Less drift. When you add a field, you do not forget to update
==.
What you pay
- A dev dependency and a build step. CI must run
build_runner, or you must commit generated files. Either choice has its own friction. - Generated files in the repository or the build. Merge conflicts in committed generated files are common.
- Slower feedback. A stale generated file produces confusing errors until you re-run the generator.
- A package to track. The generator's major versions have changed its API before. Older code that used
mapandwhenmethods needed rewriting to native patterns.
Since Dart 3, the argument for generated unions is no longer exhaustive matching, because sealed classes already provide that. The argument is the generated value semantics.
Comparison
| Concern | Enum | Hand-written sealed class | Generated union |
|---|---|---|---|
| Per-variant fields | No | Yes | Yes |
| Exhaustive `switch` | Yes | Yes | Yes |
| Value equality | Built in | You write it | Generated |
| `copyWith` | Not applicable | You write it | Generated |
| Build step | None | None | `build_runner` |
| Best for | Labels, flags, modes | A few states with distinct data | Many data-heavy states, JSON |
Gotchas
- Do not use an enum with nullable fields to fake a union.
enum Status { loading, loaded, failed }next toList<String>? itemsandObject? erroris the original problem again. - Do not create a sealed subclass for each of many near-identical cases. If variants differ only by a label, use one variant with an enum field.
- Do not add a generator to save three
==overrides. A generator has an ongoing cost. Hand-write small hierarchies and adoptfreezedwhen the boilerplate becomes a maintenance burden. - Remember the same-library rule. A sealed class can only be subtyped in its own library. If other packages must add their own variants, use an
abstract interface classinstead, and accept thatswitchwill no longer be exhaustive. - Beware wildcard
_cases. A_ =>branch in a switch over a sealed type silences the compiler when you add a variant. Prefer listing every variant.
Exercise
A checkout screen has these states. "Idle" has no data. "Submitting" has no data. "Succeeded" holds an order ID string. "Rejected" holds a reason, which is always one of cardDeclined, outOfStock, or addressInvalid. Which Dart constructs would you use, and why does the reason not become three more subclasses?
Show answer
Use a sealed class CheckoutState with four final subclasses: Idle, Submitting, Succeeded(orderId), and Rejected(reason). A sealed class is needed because Succeeded and Rejected carry different data. The reason is an enum RejectionReason { cardDeclined, outOfStock, addressInvalid } held as a field of Rejected, because the three reasons share the same shape (a label with no extra data). A switch over Rejected(reason: ...) is still exhaustive over the enum, so adding a fourth reason forces every switch to be updated. Add a generator such as freezed only if you also need generated equality, copyWith, or JSON for these types.