Sub topic 11
Handling unions with pattern matching
This chapter assumes you can declare a freezed sealed union, as in the previous chapter. It also assumes you know Dart 3 switch expressions at a basic level. Here you will learn how to consume a union safely, where the compiler's exhaustiveness check helps, and which mistakes switch that check off.
Why matching is the other half of a union
A sealed union is only useful if the code that reads it must deal with every case. Dart 3 gives you that through switch over a sealed class. Freezed's job is to generate the subclasses. Dart's job is to check that you covered them all.
Here is the union used throughout this chapter.
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;
}The class names after = matter. Each one becomes a public subclass of LoadState, and those names are what you write in patterns.
Switch expressions
A switch expression returns a value, so every case must produce one. This is the most common form for pure functions and for widget build methods.
String describe(LoadState state) => switch (state) {
LoadStateLoading() => 'Loading',
LoadStateData(:final items) => '${items.length} items',
LoadStateError(:final message) => 'Error: $message',
};Each case uses an object pattern. LoadStateData(:final items) does two things at once. It checks that the value is a LoadStateData, and it declares a local variable items bound to the items getter. The colon is shorthand for items: final items. If you want a different local name, write LoadStateData(items: final list).
Exhaustiveness is the main benefit
Suppose you later add a fourth state to the union.
const factory LoadState.empty() = LoadStateEmpty;After you re-run build_runner, every switch that lacks a LoadStateEmpty() case fails to compile. The error says the switch does not exhaustively match the type and names the missing subtype. You find every place that needs updating from the compiler output rather than from bug reports.
This only works when you leave out a catch-all. A _ => case or a default: branch matches the new state silently, so the compiler has nothing to report.
Guards with `when`
A case can carry a when condition. The case matches only if the pattern matches and the condition is true.
import 'package:flutter/material.dart';
import 'load_state.dart';
class ItemsView extends StatelessWidget {
const ItemsView({super.key, required this.state});
final LoadState state;
@override
Widget build(BuildContext context) {
return switch (state) {
LoadStateLoading() => const Center(child: CircularProgressIndicator()),
LoadStateData(:final items) when items.isEmpty =>
const Center(child: Text('Nothing here yet')),
LoadStateData(:final items) => ListView(
children: [for (final item in items) ListTile(title: Text(item))],
),
LoadStateError(:final message) => Center(child: Text('Error: $message')),
};
}
}Order matters. Dart checks cases from top to bottom, so the guarded LoadStateData case must come before the unguarded one. The compiler does not count a guarded case toward exhaustiveness, because the guard might be false. The unguarded LoadStateData(:final items) case is what completes the coverage. If you removed it, the switch would stop compiling.
Matching on the contents of a field
Patterns can look inside fields. A list pattern can replace the guard above.
String summarize(LoadState state) => switch (state) {
LoadStateLoading() => 'Loading',
LoadStateData(items: []) => 'Empty',
LoadStateData(items: [final only]) => 'Just $only',
LoadStateData(items: [final first, ...]) => 'Starts with $first',
LoadStateError(:final message) => 'Error: $message',
};Here [] matches an empty list, [final only] matches exactly one element, and [final first, ...] matches one or more. Together these three cover every List, so the compiler accepts the switch as exhaustive. Dart's exhaustiveness checker understands list lengths for this reason.
You can also combine cases with || when they share a body, as long as both sides bind the same variables (or none).
bool isBusyOrFailed(LoadState state) => switch (state) {
LoadStateLoading() || LoadStateError() => true,
LoadStateData() => false,
};Switch statements and `if-case`
Use a switch statement when each branch performs a side effect and returns nothing. The exhaustiveness check still applies to sealed types.
void log(LoadState state) {
switch (state) {
case LoadStateLoading():
print('loading');
case LoadStateData(:final items):
print('loaded ${items.length}');
case LoadStateError(:final message):
print('failed: $message');
}
}Dart 3 cases do not fall through, so no break is needed.
When you care about only one variant, if-case is shorter than a full switch.
void reportError(LoadState state) {
if (state case LoadStateError(:final message)) {
print('Report: $message');
}
}An if-case is not checked for exhaustiveness. That is correct here, since ignoring the other states is the intent.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| Pattern class not found or not visible in another file | Factory points at a private class such as `= _Data` | Name the target with a public class, such as `= LoadStateData` |
| "The type is not exhaustively matched" | A variant has no case | Add the case. Do not add `_` unless you mean it |
| Switch compiles after you add a variant | A `_` or `default` case catches it | Remove the catch-all |
| Unreachable case warning | A broad case sits above a narrower one | Move guarded or more specific cases first |
| `The method 'when' isn't defined` | Code written for freezed 2 on freezed 3 | Replace `when` and `map` with a `switch` |
| `LoadState is not a subtype of sealed` errors | Missing `sealed` modifier on the class | Declare it `sealed class`, not `abstract class` |
The version difference deserves a closer look. Freezed 2 generated when, maybeWhen, map and similar methods, and the classes behind the factories were usually private. Freezed 3 relies on Dart's native patterns instead, and it expects a sealed class for unions. Older tutorials and code still show state.when(...). If you maintain such code, check the freezed version in pubspec.yaml before migrating, and migrate one switch at a time.
Keeping state handling in one place
A pattern that scales well is to put the switch in one place per concern. A widget turns state into UI. A function turns state into a log line or analytics event. Avoid scattering is checks and casts such as (state as LoadStateData).items through your code. A cast throws at runtime if the state differs. A pattern cannot, because the variable exists only inside the matching case.
Exercise
You add const factory LoadState.empty() = LoadStateEmpty; to the union and re-run build_runner. One switch expression in ItemsView still compiles without errors. What is the most likely reason, and how do you fix it?
Show answer
The switch has a catch-all case (_ => or default), which matches the new LoadStateEmpty state silently. Remove the catch-all and add an explicit LoadStateEmpty() case. The compiler will then check exhaustiveness for you.
Exercise
Write a switch expression String label(LoadState state) that returns 'No data' when the data list is empty, the first item when there is exactly one item, and 'Many' for longer lists. Return 'Wait' for loading and the message for errors.
Show answer
String label(LoadState state) => switch (state) { LoadStateLoading() => 'Wait', LoadStateData(items: []) => 'No data', LoadStateData(items: [final only]) => only, LoadStateData(items: [, , ...]) => 'Many', LoadStateError(:final message) => message, }; The three list patterns together cover every list length, so the switch stays exhaustive without a catch-all.
Exercise
Why does LoadStateData(:final items) when items.isEmpty not satisfy exhaustiveness for the data variant on its own?
Show answer
The compiler cannot prove the guard is true for every value, so a guarded case does not count as covering its type. You need an unguarded LoadStateData case (or patterns that provably cover all values) after it.