Sub topic 10
Checking one variant with if-case
This chapter covers if-case, the form of if that tests a value against a pattern. It assumes you already have a sealed LoadState<T> hierarchy with Loading, Loaded and Failed variants. You should also know how object patterns destructure a variant inside a switch. Here you will use the same patterns when only one variant matters.
When a full switch is too much
A switch expression over a sealed type makes you handle every variant. That is the right default for code that produces a result for every state, such as a widget's build method.
Sometimes you only care about one state. You might log the first item once data has arrived. You might show a retry button only when loading failed. Writing a three-armed switch with two empty arms adds noise.
The if-case statement is the lightweight alternative. It has the form if (value case pattern). If the value matches the pattern, the then branch runs, and any variables the pattern declares are available inside it. If not, the else branch runs, or nothing happens when there is no else.
The basic form
This is a complete program. It defines the state type and uses if-case in one function.
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;
}
void printFirst(LoadState<List<String>> state) {
if (state case Loaded(data: final items) when items.isNotEmpty) {
print(items.first);
} else {
print('Nothing to show');
}
}
void main() {
printFirst(const Loading());
printFirst(const Loaded(<String>[]));
printFirst(const Loaded(['apple', 'pear']));
printFirst(const Failed('timeout'));
}Running it prints:
Nothing to show
Nothing to show
apple
Nothing to showThe condition has three parts:
stateis the value being tested.case Loaded(data: final items)is an object pattern. It checks thatstateis aLoadedand binds itsdatafield to a new variableitems. The type ofitemsis inferred asList<String>.when items.isNotEmptyis an optional guard. The pattern only counts as a match if the guard is true.
The guard can use the variables the pattern just bound. If the pattern matches but the guard is false, execution goes to the else branch. So an empty Loaded and a Loading both end up in the same place, which is correct here.
How the check runs
The diagram shows the order of evaluation. The guard runs only after the pattern matches, and the bound variables exist only on the success path.
Variable scope
Variables declared in the pattern are scoped to the then block. They are not visible in the else branch or after the if.
void show(LoadState<List<String>> state) {
if (state case Loaded(data: final items)) {
print('Have ${items.length} items');
}
// print(items); // Error: 'items' is not defined here.
}This follows from the semantics. After the if, the code cannot know whether the pattern matched, so the variable cannot exist. Scoping the variable to the success branch means you cannot read data from a state that does not have it.
If you want to bail out early and use the data in the rest of the function, if-case does not do that. Use an is! check, which promotes the type of a local variable or parameter:
int countItems(LoadState<List<String>> state) {
if (state is! Loaded<List<String>>) return 0;
return state.data.length; // state is promoted to Loaded<List<String>>
}Using if-case in collection literals
Collection literals accept if elements, and those accept case too. This is useful for building a list where one entry depends on one variant.
List<String> summaryLines(LoadState<List<String>> state) => [
'Items',
if (state case Loaded(:final data) when data.isNotEmpty)
'${data.length} entries',
if (state case Failed(:final error)) 'Last error: $error',
];Each if element is checked independently. Two conditions can both be true for a general value, though a single LoadState can match at most one of these.
The same idea works in a Flutter children list, for example if (state case Failed()) const RetryButton(). The widget is only added when the state is Failed, and no extra code is needed.
Chaining with else if
You can chain several if-case clauses, each testing a different value or pattern.
String shortLabel(LoadState<List<String>> state) {
if (state case Loaded(data: final items) when items.isNotEmpty) {
return '${items.length}';
} else if (state case Failed()) {
return '!';
} else {
return '-';
}
}This works, but look at what you wrote. It tests two variants and uses else for the rest. That is a three-way decision, and a switch expresses it with less nesting and with compiler checks. The next section explains why that matters.
The trade-off: no exhaustiveness checking
A switch over a sealed type is checked for exhaustiveness. An if-case is not, because it never claims to cover every case.
Suppose you add a fourth variant, Refreshing, to LoadState:
- Every
switchthat lacks aRefreshingarm and has no wildcard becomes a compile error. You are forced to decide what each screen does. - Every
if-casekeeps compiling. Code with anelsebranch sendsRefreshinginto that branch silently.
Neither behavior is wrong. The point is to choose on purpose:
| Situation | Use |
|---|---|
| The result must be defined for every state | `switch` expression |
| You react to one variant and ignoring the rest is correct | `if-case` |
| You need two or three variants, each with different behavior | `switch` |
| You branch on one variant but the `else` has real logic | `switch`, so new variants are flagged |
A good test is to ask what should happen when someone adds a new state. If the answer is "the compiler should make me look at this code", use switch. If the answer is "nothing, this code does not care", use if-case.
Common errors
Forgetting final or var on the binding
// Wrong: 'items' is treated as a constant to compare against.
if (state case Loaded(data: items)) { /* ... */ }
// Right:
if (state case Loaded(data: final items)) { /* ... */ }Without final or var, a bare identifier inside a pattern is a constant expression. If items is not a constant, the analyzer reports an error. If you want to match a specific value, write the constant intentionally. If you want to capture, add final.
Using = instead of case
if (state = Loaded(...)) is an assignment, not a pattern test. The keyword case is what starts the pattern. Dart's analyzer rejects this for a non-boolean if condition, but the mistake is easy to make when switching from other languages.
Using a guard where a pattern would do
if (state case Loaded() when state is Loaded<List<String>>) repeats a check the pattern already performs. Put type and shape checks in the pattern, and use when only for conditions that depend on values.
Expecting a negated form
There is no if (state case not Loaded()) to run code when the state is anything but Loaded. Pattern variables could not be bound in a non-matching branch anyway. Use an is! check, or put the code in the else branch.
Matching a nullable value
Patterns also work on non-sealed values. The null-check pattern ? and the null-assert pattern ! are common:
void greet(Map<String, Object?> json) {
if (json case {'name': String name, 'age': int age} when age >= 18) {
print('Hello, $name');
}
}The map pattern requires both keys to be present with the right types. A missing key, a null, or a wrong type all lead to a non-match rather than an exception. This makes if-case a compact replacement for chains of containsKey and is checks when you read loosely typed data.
Putting it together
Here is a function that uses if-case for the case it cares about, and leaves the rest of the screen to a switch elsewhere:
String? retryHint(LoadState<List<String>> state) {
if (state case Failed(:final error)) {
return 'Tap to retry ($error)';
}
return null;
}The build method keeps the exhaustive switch from the earlier chapter. A small helper like this one handles a side detail, so that build does not need to grow a branch for it.
Exercise
Write a function String? errorMessage(LoadState<List<String>> state) that returns the error text as a string when the state is Failed, and null for every other state. Use if-case, not switch.
Show answer
Use if (state case Failed(:final error)) { return '$error'; } and then return null; after the if. The pattern matches only Failed and binds its error field. Every other variant skips the block and falls through to return null.
Exercise
You add a new variant Refreshing<T> to LoadState. A function uses if (state case Loaded(:final data)) { ... } else { showSpinner(); }. What happens at compile time, and what would you change if Refreshing needs its own behavior?
Show answer
Nothing happens at compile time, because if-case has no exhaustiveness check. At run time Refreshing goes into the else branch and shows the spinner. If Refreshing needs distinct behavior, convert the code to a switch expression with one arm per variant and no wildcard. The compiler will then flag every place that does not yet handle Refreshing.