Sub topic 10
Sealed unions for multiple states
This chapter assumes you can write a basic freezed class with @freezed, a part directive and a redirecting const factory. You should also know how to run build_runner. You need Dart 3 syntax such as switch expressions, but pattern matching gets its own chapter, so only the basics appear here.
The problem: one class, many shapes
A screen that loads data is rarely in a single state. It is loading, it has data, or it failed. A common first attempt packs all of this into one data class:
class LoadStateBad {
const LoadStateBad({
this.isLoading = false,
this.items,
this.errorMessage,
});
final bool isLoading;
final List<String>? items;
final String? errorMessage;
}This class can describe states that should never exist. isLoading: true together with errorMessage: 'boom' compiles and runs. Every reader of the class must also remember which combinations are valid and null-check every field. The type system gives no help.
A union type (also called a sum type or tagged union) fixes this. It is a type whose value is exactly one of several named variants. Each variant carries only the fields that make sense for it. A value cannot be "loading with an error", because no such variant exists.
Declaring a union with freezed
In freezed, you create a union by declaring more than one const factory constructor in the same class. Each constructor becomes one variant:
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;
}Three parts of this declaration matter:
sealed class. A sealed class can only be extended inside its own library. The generated variant classes live inload_state.freezed.dart, which is part of that library. Because the compiler knows the complete list of subclasses, it can check aswitchfor exhaustiveness.- The constructor name, such as
.loading,.dataand.error. This is the name callers use to create a value:LoadState.data(['a', 'b']). - The redirect target, such as
LoadStateData. This is the name of the concrete class that freezed generates for the variant. You choose it, and you use it inswitchpatterns andischecks.
Run the generator as in the setup chapter. After that, you can create and inspect values:
void main() {
const LoadState a = LoadState.loading();
const LoadState b = LoadState.data(['x', 'y']);
const LoadState c = LoadState.data(['x', 'y']);
print(a is LoadStateLoading); // true
print(b == c); // true
print(b == a); // false
print(b); // LoadState.data(items: [x, y])
}Each variant gets the same generated members you saw for plain freezed classes. That means value equality, hashCode, toString and copyWith. Equality compares the variant type first and then the fields, so LoadState.data([]) never equals LoadState.loading().
Reading a union: a first look
Fields exist only on the variant that declares them. The base type LoadState has no items getter, because loading has no items. To read items, you first need to know you hold a LoadStateData. A Dart 3 switch expression does this and also checks that you covered every variant:
String label(LoadState state) => switch (state) {
LoadStateLoading() => 'Loading',
LoadStateData(:final items) => '${items.length} items',
LoadStateError(:final message) => 'Error: $message',
};If you later add a fourth constructor and forget to update label, the compiler reports a missing case. The next chapter covers patterns in depth, including guards, nested patterns and if-case.
An is check also works, and Dart promotes the type inside the branch:
int itemCount(LoadState state) {
if (state is LoadStateData) {
return state.items.length;
}
return 0;
}The is check gives no exhaustiveness guarantee. Prefer switch when you need to handle every variant.
Shared properties
When every constructor declares a field with the same name and type, freezed exposes it on the base class. This is useful for data such as an id that every variant carries:
import 'package:freezed_annotation/freezed_annotation.dart';
part 'event.freezed.dart';
@freezed
sealed class Event with _$Event {
const factory Event.tapped(String id, double x, double y) = TappedEvent;
const factory Event.scrolled(String id, double delta) = ScrolledEvent;
}
String eventId(Event e) => e.id; // allowed: every variant has `id`If one variant lacked id, or declared it with a different type, e.id would not compile on Event.
Different fields, named parameters and defaults
Union constructors accept everything a normal freezed constructor does. These include named parameters, required, @Default and nullable fields:
import 'package:freezed_annotation/freezed_annotation.dart';
part 'upload_state.freezed.dart';
@freezed
sealed class UploadState with _$UploadState {
const factory UploadState.idle() = UploadIdle;
const factory UploadState.uploading({
@Default(0.0) double progress,
}) = UploadUploading;
const factory UploadState.failed({
required String reason,
@Default(false) bool retryable,
}) = UploadFailed;
}copyWith is generated per variant and only on the concrete type. You can call copyWith(progress: 0.5) on a UploadUploading, but not on a plain UploadState. To change a value whose variant you do not know yet, narrow the type first:
UploadState advance(UploadState s) => switch (s) {
UploadUploading(:final progress) =>
s.copyWith(progress: (progress + 0.1).clamp(0.0, 1.0)),
_ => s,
};Note that copyWith never changes the variant. To move from uploading to failed, construct a new value with UploadState.failed(...).
Unions and JSON
A union can have fromJson and toJson too. Because a JSON object does not say which variant it holds, the generated code writes an extra key into the output and reads it back. By default the key is runtimeType, and its value is the constructor name. You can change both:
import 'package:freezed_annotation/freezed_annotation.dart';
part 'shape.freezed.dart';
part 'shape.g.dart';
@Freezed(unionKey: 'type', fallbackUnion: 'unknown')
sealed class Shape with _$Shape {
@FreezedUnionValue('circle')
const factory Shape.circle(double radius) = Circle;
@FreezedUnionValue('square')
const factory Shape.square(double side) = Square;
const factory Shape.unknown() = UnknownShape;
factory Shape.fromJson(Map<String, dynamic> json) => _$ShapeFromJson(json);
}With this declaration, {"type": "circle", "radius": 2.0} decodes to Shape.circle(2.0). The fallbackUnion setting names the constructor to use when type is missing or holds an unknown value. Without a fallback, fromJson throws on an unrecognized tag. A fallback constructor must take no required parameters.
Version differences
Freezed 3 changed how unions are declared and consumed. If you read older tutorials or maintain an older project, watch for these differences:
| Topic | Freezed 2.x | Freezed 3.x |
|---|---|---|
| Declaring a union | `class` with `@freezed` | Needs the `sealed` keyword |
| Declaring a single-constructor class | `class` | Needs `abstract` (or `sealed`) |
| Consuming a union | `when`, `map`, `maybeWhen` and similar helpers | Dart 3 `switch` and patterns; the helpers are removed |
Code that calls state.when(...) will not compile after upgrading to freezed 3. Replace each call with a switch expression. Check the version in your pubspec.yaml before copying examples from older tutorials.
Common problems
- "Missing concrete implementation" or an undefined class error. The redirect target, such as
LoadStateData, exists only after generation. Rundart run build_runner build --delete-conflicting-outputsand confirm thepartline matches the file name. The getter 'items' isn't defined for the type 'LoadState'. The field belongs to one variant. Narrow the type withswitchoris.- Switch not exhaustive after adding a variant. This is the compiler doing its job. Add the new case. Avoid a
_wildcard on unions you own, because it hides this warning. - A union holding many optional fields. If every variant has the same nullable fields, you probably wanted a plain data class instead.
When to choose a union
Use a union when the states are mutually exclusive and each one carries different data. Loading, data and error is the classic case. Other examples are an authentication state (signed out, signing in, signed in with a user), a form submission, or a parsed message type. Use a plain freezed class when all instances have the same fields and differ only in value. A union adds a class per variant and a switch at each use site. That cost is worth paying only when it removes impossible states.
Exercise
You have sealed class Auth with _$Auth with constructors signedOut(), signingIn() and signedIn(User user). A teammate writes String name(Auth a) => a.user.name; and gets a compile error. Why does it fail, and how do you write a correct version that returns 'guest' when nobody is signed in?
Show answer
Only the signedIn variant declares user, so the base type Auth has no user getter. Narrow the type first, for example with a switch expression: String name(Auth a) => switch (a) { AuthSignedIn(:final user) => user.name, _ => 'guest' };. Here AuthSignedIn stands for whatever redirect class name you gave the signedIn constructor. Listing AuthSignedOut() and AuthSigningIn() explicitly instead of _ is better, because the compiler then flags any variant you add later.
Exercise
A sealed freezed union has fromJson, and the server starts sending a new tag, "triangle", that your app does not know. What happens by default, and how can you make the app keep working?
Show answer
By default fromJson throws because the tag matches no constructor. Set fallbackUnion in @Freezed(...) to the name of a no-argument constructor, such as unknown. Unrecognized or missing tags then decode to that variant, and the app can handle it in its switch.