Sub topic 11
Handling unions with pattern matching
This chapter assumes you understand Dart classes, named parameters, null safety, and basic freezed unions. It also assumes Dart 3, including sealed classes, pattern matching, and switch expressions.
A union, also called a sum type, represents one value that can have several different shapes. A loading state has no data. A data state has items. An error state has a message. These states should not be represented by unrelated nullable fields such as isLoading, items, and error because invalid combinations become possible.
A union describes valid states
A freezed union declares one constructor for each valid state:
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;
}After running the code generator, Dart knows about three concrete classes:
LoadStateLoadingLoadStateDataLoadStateError
Every LoadState value is exactly one of these types. A data state always has an items list, and an error state always has a message.
Switch expressions check every case
A switch expression returns a value. Pattern matching checks both the type of the union and the fields inside that type:
String describe(LoadState state) => switch (state) {
LoadStateLoading() => 'Loading',
LoadStateData(:final items) => '${items.length} items',
LoadStateError(:final message) => 'Error: $message',
};LoadStateData(:final items) matches a data state and copies its items property into a local variable. LoadStateError(:final message) does the same for message.
Because LoadState is sealed, the Dart analyzer knows its possible subtypes. If you add another constructor, such as empty(), existing switches that do not handle it produce an exhaustiveness error. This turns a new state into a visible checklist of code that needs updating.
Use patterns to build UI decisions
A Flutter widget can use the same expression to select a widget:
String screenMessage(LoadState state) => switch (state) {
LoadStateLoading() => 'Please wait',
LoadStateData(:final items) when items.isEmpty => 'No items found',
LoadStateData(:final items) => 'Showing ${items.length} items',
LoadStateError(:final message) => message,
};The when clause adds a condition to a pattern. The empty-data case must come before the general data case. If the general case came first, it would match empty lists too, so the later case would never be reached.
You can also match constant values directly:
String firstItem(LoadState state) => switch (state) {
LoadStateData(items: [final first, ...]) => first,
_ => 'No first item',
};The list pattern matches a data state whose list contains at least one item. The _ pattern is a fallback. Use it when several cases intentionally share the same behavior. Avoid it when you want the compiler to warn you about every future union case.
Common matching errors
- Matching
LoadState.datainstead of the generated typeLoadStateData. - Forgetting to run
build_runnerafter changing a constructor. - Placing a broad pattern before a more specific
whenpattern. - Destructuring a nullable field as non-nullable.
- Using
_when every state needs different behavior.
Exercise
Add an empty() constructor to LoadState and update describe so it returns No items for that state. Why should the compiler help you find the missing branch?
Show answer
Add const factory LoadState.empty() = LoadStateEmpty; and a LoadStateEmpty() => 'No items' branch. Because the union is sealed, the analyzer can detect that the switch is no longer exhaustive.