Sub topic 10
Checking one variant with if-case
This chapter assumes Dart 3 or later, including classes, null safety, generics, and object patterns. It also assumes basic Flutter widgets and the build method. The previous chapter introduced a sealed LoadState hierarchy with Loading, Loaded, and Failed variants.
A full switch is useful when every state needs a different result. Sometimes you only need to act when one particular variant appears. Dart's if-case statement handles that situation. It tests a pattern and makes the matched fields available inside the if block.
Matching one state variant
This condition matches a Loaded object and extracts its data field:
if (state case Loaded(data: final items)) {
print('Loaded ${items.length} items');
}The pattern has two jobs:
Loaded(...)checks the runtime variant.data: final itemsreads thedatagetter and stores it in a local variable nameditems.
If state is Loading or Failed, the block is skipped. Unlike an exhaustive switch, if-case does not require code for the variants that do not match.
The following complete program checks several variants:
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) {
if (state case Loaded(data: final items)) {
return 'Loaded ${items.length} items';
}
if (state case Failed(error: final error)) {
return 'Load failed: $error';
}
return 'Loading';
}
void main() {
print(describe(const Loaded<List<String>>(['Dart', 'Flutter'])));
print(describe(const Failed<List<String>>('Network unavailable')));
print(describe(const Loading<List<String>>()));
}The variable items exists only inside the first if block. Dart knows its type from the generic state and the pattern, so no cast is needed.
Adding a condition with `when`
A pattern can match a variant while a when guard checks one of its values. A guard is a boolean condition attached to a case:
if (state case Loaded(data: final items) when items.isNotEmpty) {
print('The first item is ${items.first}');
}This block runs only when both conditions are true:
stateis aLoadedstate.- Its list contains at least one item.
A guard prevents unsafe operations such as reading items.first from an empty list. You can then handle the remaining loaded case separately:
String describeLoaded(LoadState<List<String>> state) {
if (state case Loaded(data: final items) when items.isNotEmpty) {
return 'First item: ${items.first}';
}
if (state case Loaded()) {
return 'Nothing loaded yet';
}
return 'The request is still in progress or failed';
}The second pattern matches any Loaded value. Since the first condition already returned for non-empty lists, the second block represents an empty loaded result.
`if-case` in Flutter code
In a Flutter event handler, if-case can keep a one-variant action focused:
void showFirstItem(LoadState<List<String>> state) {
if (state case Loaded(data: final items) when items.isNotEmpty) {
print(items.first);
}
}For a widget's complete visual output, an exhaustive switch is usually clearer because loading, success, and failure all need an explicit UI. For a small action, logging operation, or optional side effect, if-case avoids unnecessary branches.
Exercise
What does this condition guarantee before its block runs? if (state case Loaded(data: final items) when items.isNotEmpty)
Show answer
It guarantees that state is a Loaded value, binds its data to items, and confirms that the list is not empty.