Sub topic 5
Destructuring state with object patterns
This chapter assumes you know Dart classes, final fields, null safety and basic generics. It also assumes you have read the previous chapters, which introduced sealed classes and switch expressions. You need Dart 3 or later.
An object pattern checks that a value has a certain type and reads some of its fields in the same step. This chapter covers the full syntax, how matching works internally, and the edge cases that surprise people.
The shape of an object pattern
Here is the state hierarchy from earlier chapters, with a function that uses object patterns in every case. Save it as one file and run it with dart run.
sealed class LoadState<T> {
const LoadState();
}
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.error);
final Object error;
}
String describe(LoadState<List<String>> state) => switch (state) {
Loading() => 'Loading...',
Loaded(data: final items) when items.isEmpty => 'Nothing here yet',
Loaded(data: final items) => '${items.length} items',
Failed(error: final e) => 'Error: $e',
};
void main() {
print(describe(const Loading()));
print(describe(const Loaded(<String>[])));
print(describe(const Loaded(['a', 'b'])));
print(describe(Failed(Exception('boom'))));
}The program prints Loading..., Nothing here yet, 2 items and Error: Exception: boom.
Each case has a type name followed by parentheses. Inside the parentheses you write zero or more getterName: subpattern pairs.
Loading()has no pairs. It is a pure type test: "is this value aLoading?"Loaded(data: final items)tests the type, readsstate.data, and binds the result to a new variable nameditems.final itemsis a variable pattern. It always matches and captures the value. Usevarinstead offinalif you need to reassign it.
The variables exist only inside the matched case, including its when guard and its result expression.
What the compiler does with a pattern
A case is not just syntax for an is check followed by a cast. Matching goes through these steps, in order.
Three consequences follow.
- After the type test succeeds, the value is promoted to that type. In
Loaded(data: final items),itemshas the typeList<String>, notTorObject?. You don't write a cast. - Cases are tried from top to bottom, and the first match wins. Put narrow cases (patterns with guards or literals) before broader ones.
- Subpatterns are not limited to variable patterns. Any pattern can go in that position.
Getters, not fields
The names in an object pattern are getters. A getter can be a plain final field, a computed property, or an inherited member. This means you can match on values that the class derives.
class Page {
const Page(this.items, this.total);
final List<String> items;
final int total;
bool get isLast => items.length >= total;
}
String pageLabel(Page page) => switch (page) {
Page(isLast: true, items: [final only]) => 'Last page, one item: $only',
Page(isLast: true) => 'Last page',
Page(:final total) => 'More to load, $total in total',
};Here isLast: true is a constant pattern. It matches when the getter returns a value equal to true.
Matching calls the getter, so keep getters cheap and free of side effects. The language doesn't promise how many times a getter runs, or in what order, when several cases name it.
Shorthand and rename
When the variable should have the same name as the getter, drop the repetition. :final data means data: final data.
| Written form | Equivalent | Binds |
|---|---|---|
| `Loaded(data: final items)` | none, explicit | `items` |
| `Loaded(:final data)` | `Loaded(data: final data)` | `data` |
| `Loaded(:var data)` | `Loaded(data: var data)` | mutable `data` |
| `Loaded(data: List<String> items)` | typed variable pattern | `items`, checked as `List<String>` |
| `Loaded()` | type test only | nothing |
A typed variable pattern such as List<String> items adds a runtime type test. It fails to match if the value has another type. A plain final items takes whatever static type the getter has.
Nesting patterns
A subpattern can itself be an object pattern, a list pattern, a record pattern, a constant or a relational pattern. This lets one case look several levels deep.
sealed class LoadState<T> {
const LoadState();
}
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.error);
final Object error;
}
String detail(LoadState<List<String>> state) => switch (state) {
Loading() => 'waiting',
Loaded(data: []) => 'empty list',
Loaded(data: [final only]) => 'one item: $only',
Loaded(data: [final first, ...final rest]) =>
'$first and ${rest.length} more',
Failed(error: FormatException(:final message)) => 'bad format: $message',
Failed(:final error) => 'failed: $error',
};
String label(LoadState<int>? state) => switch (state) {
null => 'no state yet',
Loading() => 'loading',
Loaded(data: < 0) => 'negative',
Loaded(data: final n) => 'value $n',
Failed() => 'failed',
};
void main() {
print(detail(const Loaded(['a', 'b', 'c'])));
print(detail(Failed(FormatException('nope'))));
print(detail(Failed('timeout')));
print(label(null));
print(label(const Loaded(-4)));
const Loaded<int> ready = Loaded(42);
final Loaded(:data) = ready;
print(data);
}The output is:
a and 2 more
bad format: nope
failed: timeout
no state yet
negative
42Points worth studying in this file:
Loaded(data: [])matches only an empty list. The three list cases ([], one element, and one element plus a rest) together cover every possible list length, and the compiler can verify that.Failed(error: FormatException(:final message))looks inside theObjectstored inerror. The nested object pattern performs its own type test, so it only matches when the error really is aFormatException.- The
Failed(:final error)case that follows catches every other error. Order matters here. If you swapped the twoFailedcases, the specific one could never run. < 0is a relational pattern. It compares the getter's value with a constant.- The last lines use a pattern in a variable declaration.
final Loaded(:data) = ready;is allowed becausereadyis statically aLoaded<int>, so the pattern can't fail. If the static type wereLoadState<int>, the compiler would reject it, because the pattern could fail.
Nullable values
A type test never matches null. The state LoadState<int>? has one more possible value than LoadState<int>, so label above needs the null case. Without it, the compiler reports a non-exhaustive switch.
The same holds for subpatterns. If a getter returns String?, then Foo(name: final n) matches both a string and null, and n has type String?. To require a non-null value, write Foo(name: final String n) or Foo(name: final n?). The second form is a null-check pattern. It fails on null and binds n as the non-nullable type.
Common mistakes
- Binding a name that shadows an outer variable.
Loaded(:final data)inside a method that already has a parameter nameddataintroduces a newdatafor that case only. The outer one is still reachable outside the case, but the clash makes the code hard to read. Rename withdata: final items. - Using
=instead of=>in a switch expression. Each case in a switch expression ends in=>. A switch statement usescase ...:. Mixing the two forms causes confusing syntax errors. - Expecting the pattern to match a supertype.
Loaded()does not match a plainLoadState. The value must actually be aLoaded. - Forgetting that unnamed patterns don't capture.
Loaded()checks the type but gives you no access todata. Add a pair when you need the contents. - Putting a broad case first. A case such as
Loaded(:final data)placed aboveLoaded(data: [])makes the narrower case unreachable. The compiler warns you with an unreachable-case diagnostic.
When to prefer a plain `is` check
For a single type test with no fields to read, if (state is Loading) is shorter. Object patterns pay off when you need to read fields, bind them and test them in one step, or when you want the compiler to check the whole set of cases. The next chapters build on that second benefit.
Exercise
Given LoadState<List<String>> state = Loading();, what does if (state case Loaded(data: final items)) { print(items); } do? Then write an object pattern that matches a Failed whose error is a TimeoutException and binds its duration getter to a variable named limit (it is nullable, and the case should only match when it is not null).
Show answer
The if body does not run, and nothing prints, because the type test Loaded fails for a Loading value. The getter data is never read. The pattern for the second part is Failed(error: TimeoutException(duration: final limit?)). The trailing ? is a null-check pattern: it fails when duration is null, and otherwise binds limit as a non-nullable Duration. TimeoutException comes from dart:async, so the file needs import 'dart:async';.