Sub topic 3
Sealed Unions for Multiple States
This chapter assumes you know Dart classes, named parameters, and null safety. You should already have freezed and build_runner set up, and you should understand Dart 3 sealed classes and switch expressions.
Sealed unions for multiple states
A union is one type that can take one of several forms. In freezed, you declare each form as a factory constructor on a sealed class. Dart knows the full list of forms, so it can check that your code handles every one.
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;
}Handling unions with pattern matching
A switch expression on a sealed type must cover every variant. Use :final to read the fields of each variant.
String describe(LoadState state) => switch (state) {
LoadStateLoading() => 'Loading',
LoadStateData(:final items) => '${items.length} items',
LoadStateError(:final message) => 'Error: $message',
};Modeling loading, data and error state
A common alternative is one class with isLoading, items and error fields. Those fields can combine into impossible states, such as loading with an error present. A union allows only one state at a time.
| Approach | Possible invalid combinations |
|---|---|
| Several flags and nullable fields | Yes, for example `isLoading` true with `error` set |
| Sealed union | No, each variant holds only its own data |
Updating nested objects
When a field holds another freezed class, copyWith.field(...) updates the inner object and returns a new outer object.
import 'package:freezed_annotation/freezed_annotation.dart';
part 'user.freezed.dart';
@freezed
abstract class Address with _$Address {
const factory Address({required String city}) = _Address;
}
@freezed
abstract class User with _$User {
const factory User({required String name, required Address address}) = _User;
}
User move(User user) => user.copyWith.address(city: 'Oslo');Testing models with value equality
Generated == and hashCode let you compare whole objects. The test below uses the Address class from the previous section.
import 'package:test/test.dart';
void main() {
test('equal fields mean equal objects', () {
const a = Address(city: 'Oslo');
const b = Address(city: 'Oslo');
expect(a, equals(b));
expect(a.hashCode, b.hashCode);
});
}Common pitfalls and version differences
- Stale generated code. After you edit a freezed class, rerun
dart run build_runner build --delete-conflicting-outputs. A missingpartline causes errors about undefined_$Namemembers. - Shallow immutability. Freezed does not make a
Listfield unchangeable. Use aconstlist orList.unmodifiable. - Version differences. Freezed 3 requires Dart 3, and its data classes use the
abstractmodifier. Freezed 2 code used@freezed classwithout it. Check the freezed version inpubspec.yamlbefore you copy examples.
Exercise
Why does the switch in describe need no default case, and what happens if you add a fourth variant to LoadState?
Show answer
LoadState is sealed and the switch lists all three variants, so the compiler knows the switch is exhaustive. A fourth variant makes the switch fail to compile until you add a case for it.