Sub topic 1
Why flags and nullable fields allow impossible states
Prerequisites
This chapter assumes you already know the following:
- Dart basics: classes, constructors,
finalfields, and null safety. - Basic generics in Dart, such as
List<String>. - Basic Flutter widgets and the
buildmethod. - Dart 3 or later is installed, because later chapters use sealed classes and patterns.
You do not need to know sealed classes or pattern matching yet. This chapter explains the problem they solve. The rest of the tutorial shows the solution.
The usual way to model a loading screen
Most screens that fetch data pass through the same stages. The screen is loading, then it shows data, or it shows an error. A common first model puts all of that in one class:
class ItemsState {
const ItemsState({
this.isLoading = false,
this.items,
this.error,
});
final bool isLoading;
final List<String>? items;
final Object? error;
}This looks reasonable. Each field maps to something the UI needs. The widget reads the fields and decides what to draw:
import 'package:flutter/material.dart';
class ItemsView extends StatelessWidget {
const ItemsView({super.key, required this.state});
final ItemsState state;
@override
Widget build(BuildContext context) {
if (state.isLoading) {
return const Center(child: CircularProgressIndicator());
}
if (state.error != null) {
return Center(child: Text('Something went wrong: ${state.error}'));
}
return ListView(
children: [for (final item in state.items!) ListTile(title: Text(item))],
);
}
}The code compiles and works on the happy path. The problems appear when you ask which combinations of field values the class permits.
Counting the possible states
The class has three fields:
isLoadinghas 2 values:trueorfalse.itemshas 2 cases:nullor a list. A list can be empty or not, but treat it as one case for now.errorhas 2 cases:nullor an object.
The type allows 2 × 2 × 2 = 8 combinations. The screen has only three meaningful states. The table lists all eight.
| `isLoading` | `items` | `error` | Meaning |
|---|---|---|---|
| true | null | null | Loading. Valid. |
| false | list | null | Loaded. Valid. |
| false | null | error | Failed. Valid. |
| false | null | null | Nothing fetched yet, or a bug. Unclear. |
| true | list | null | Refreshing? Or a stale flag? Unclear. |
| true | null | error | Loading and failed at once. Impossible. |
| false | list | error | Loaded and failed at once. Impossible. |
| true | list | error | Everything at once. Impossible. |
Three rows are valid. One more is ambiguous. Four combinations are either impossible or have no agreed meaning. Nothing in the type stops code from creating them. These are called impossible states: values the type permits but your feature should never be in.
The number also grows quickly. Adding one more boolean, such as isRefreshing, doubles the table to 16 rows. Adding a second nullable field doubles it again.
The diagram below shows the gap between what the type allows and what the feature needs.
How impossible states get created
The compiler accepts every row of the table, so any code path can produce an invalid one. Typical causes:
- Forgotten resets. A retry sets
isLoading = truebut leaves the olderrorin place. The user sees a spinner or an error depending on whichifcomes first inbuild. - Partial updates. A fetch succeeds and the code sets
itemsbut forgets to setisLoadingback tofalse. The spinner never goes away. - Copy-with mistakes. A
copyWithmethod that keeps old values by default makes stale fields easy to carry into a new state. - Async ordering. Two requests finish in a different order than they started. The second response sets
itemswhile the first setserror, and both survive.
Here is the retry case in code:
class ItemsState {
const ItemsState({
this.isLoading = false,
this.items,
this.error,
});
final bool isLoading;
final List<String>? items;
final Object? error;
ItemsState copyWith({
bool? isLoading,
List<String>? items,
Object? error,
}) {
return ItemsState(
isLoading: isLoading ?? this.isLoading,
items: items ?? this.items,
error: error ?? this.error,
);
}
}
void main() {
const failed = ItemsState(error: 'timeout');
// The user taps "Retry". The code only flips the loading flag.
final retrying = failed.copyWith(isLoading: true);
print('isLoading: ${retrying.isLoading}');
print('error: ${retrying.error}');
}The output is:
isLoading: true
error: timeoutThe new state is loading and failed at the same time. This is row six of the table. The code compiles, and no test fails unless someone wrote one for this exact case. The ?? operator also makes it impossible to clear a field by passing null, which is a second reason copyWith is risky here.
The cost shows up in the UI
The build method above hides several decisions in the order of its if statements:
- If
isLoadingis true, it ignoreserroranditems. - If
erroris not null, it ignoresitems. - Otherwise it assumes
itemsis not null and usesstate.items!.
The ! is the weak point. It tells the compiler to trust you that the list exists. For the all-empty row (false, null, null) the list does not exist, and the screen throws a null check error at runtime.
void main() {
const initial = ItemsState();
// Same logic as the build method: not loading, no error, so read items.
print(initial.items!.length);
}Running this throws Null check operator used on a null value. The static type system did not warn you, because items is legitimately nullable in the class.
> The ordering of the checks is also a hidden rule. Another developer who reorders the if statements changes what the user sees for the ambiguous states, and no compiler message tells them.
Because block quotes are not used in this chapter, the same point as a callout:
Defensive fixes and why they fall short
Teams usually try to patch the problem before changing the model. The common patches help, but each leaves a gap.
| Approach | What it fixes | What it leaves open |
|---|---|---|
| Assertions in the constructor | Catches bad combinations in debug builds | Release builds skip `assert`, and every new field needs a new assertion |
| Private constructor plus named factories | Limits how states are created | The fields are still readable in every combination, so `build` still needs `!` |
| A status enum next to the data fields | Gives each stage a name | The data fields can still disagree with the enum |
| Careful code review | Catches mistakes you can see | Does not scale and does not protect future edits |
The status enum is the most popular patch, so look at it more closely:
enum Status { loading, loaded, failed }
class ItemsState {
const ItemsState({
required this.status,
this.items,
this.error,
});
final Status status;
final List<String>? items;
final Object? error;
}The enum makes build easier to read, because you can switch on status. It does not remove the problem. The values Status.loaded with items == null and Status.failed with error == null are still legal. The data lives beside the status instead of inside it, so the two can drift apart.
What a better model looks like
The root problem is that the type describes the union of all fields, while the feature has separate shapes. In each state only some data exists:
- Loading has no data and no error.
- Loaded has a list and no error.
- Failed has an error and no list.
A good model makes those shapes the only values that can exist. Each state carries exactly its own data. A state that has an error does not have an items field at all, so there is nothing to forget to clear and nothing to null-check. If the type can only represent valid states, the invalid ones cannot be constructed.
This idea is often phrased as "make impossible states unrepresentable". It moves the check from runtime and code review to compile time.
Dart 3 gives you two features that make this practical:
- Sealed classes define a closed family of subtypes, one per state.
- Pattern matching with switch expressions lets you read each state's data safely and makes the compiler verify that you handled every state.
The following chapters build this up step by step. Here is a preview of the shape, which the next chapter explains:
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;
}Count the states this type allows. There are exactly three. Loaded always has data, which is non-null by its type. Failed always has an error. Loading has neither. There is no way to write a "loading with an error" value, so the retry bug from earlier cannot be written. To retry, you must replace the whole state with a new Loading(), which carries no leftover error.
A quick way to audit your own state class
You can apply the counting exercise to any state class in your own code. Use this checklist:
- List each field and the number of distinct cases it has. Treat
boolas 2, a nullable field as 2, and an enum as its number of values. - Multiply the counts to get the number of combinations the type allows.
- Write down the states your feature actually has.
- Compare the two numbers. Every combination beyond your list is an impossible state.
- Search the code for
!on those fields and forcopyWithcalls that update only some of them. These are the places such states are most likely to appear.
The result is a concrete measure of how much risk the model carries, and it tells you where to focus when you refactor.
Exercise
A state class has bool isLoading, bool isRefreshing, String? error, and List<int>? data. How many combinations does the type allow when you count each field as two cases? Give one combination that no feature should ever be in.
Show answer
The type allows 2 × 2 × 2 × 2 = 16 combinations. One impossible example is isLoading: true, isRefreshing: true, error set, and data set, since the screen cannot be loading, refreshing, failed, and loaded at once. Another is isLoading: true with error set.
Exercise
A developer adds a Status enum with loading, loaded, and failed to a class that still has nullable items and error fields. Why does this not remove the need for ! on items in the loaded branch?
Show answer
The enum value and the data fields are independent, so the type still allows Status.loaded with items == null. The compiler cannot connect the status to the data, so reading items as non-null still needs !, which crashes if the combination occurs.
Exercise
In the copyWith example, why does failed.copyWith(isLoading: true) produce an invalid state, and what property of a better model would prevent it?
Show answer
copyWith keeps every field you do not pass, so the old error survives into the new state, which is then loading and failed at once. A better model has one type per state with only that state's data, so a retry replaces the whole value with a Loading that has no error field to carry over.