Sub topic 12
Modeling loading, data and error state
This chapter assumes you can write Dart classes with named parameters, know Dart 3 switch expressions and sealed classes, and have already set up freezed and build_runner as in the earlier chapters. You will model the three states of an asynchronous screen as one sealed union, render it with an exhaustive switch, and handle the edge cases that a three-case model leaves out.
The problem with flag-based state
Most first attempts at a loading screen use separate fields:
class ItemsState {
bool isLoading = true;
List<String>? items;
String? error;
}Nothing stops this object from holding isLoading == true, a non-null items and a non-null error at once. Every widget that reads it must decide what that combination means, and different widgets decide differently. The class permits many more combinations than the screen has real states.
A sealed union fixes this by making each state its own type. A loading value has no items field to misread. A data value always has items. An error value always has a message.
The three-case union
Create load_state.dart:
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;
}Run dart run build_runner build --delete-conflicting-outputs to generate load_state.freezed.dart. The name after = is the public class for that case, so you can name it in patterns. Each case gets its own generated equality, hashCode, toString and copyWith.
The legal transitions form a small graph:
A controller that produces states
Flutter's ValueNotifier is enough to hold the current state. Any change that assigns a new, unequal value notifies listeners.
import 'package:flutter/foundation.dart';
import 'load_state.dart';
class ItemsController extends ValueNotifier<LoadState> {
ItemsController(this._fetch) : super(const LoadState.loading());
final Future<List<String>> Function() _fetch;
bool _disposed = false;
Future<void> load() async {
value = const LoadState.loading();
try {
final items = await _fetch();
if (_disposed) return;
value = LoadState.data(items);
} catch (e) {
if (_disposed) return;
value = LoadState.error(e.toString());
}
}
@override
void dispose() {
_disposed = true;
super.dispose();
}
}The _disposed check matters. If the user leaves the screen while the request is running, assigning value on a disposed notifier throws. Checking the flag after each await avoids that.
ValueNotifier only notifies when the new value is not == to the old one. Because freezed generates value equality, assigning const LoadState.loading() while already loading does nothing, which is usually what you want. It also means two data states holding equal lists do not trigger a rebuild.
Rendering with an exhaustive switch
The widget turns each state into UI. There is no default branch, so the compiler checks that every case is handled.
import 'package:flutter/material.dart';
import 'items_controller.dart';
import 'load_state.dart';
class ItemsView extends StatelessWidget {
const ItemsView({super.key, required this.controller});
final ItemsController controller;
@override
Widget build(BuildContext context) {
return ValueListenableBuilder<LoadState>(
valueListenable: controller,
builder: (context, state, _) => switch (state) {
LoadStateLoading() =>
const Center(child: CircularProgressIndicator()),
LoadStateData(:final items) => ListView(
children: [for (final item in items) ListTile(title: Text(item))],
),
LoadStateError(:final message) => Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(message),
ElevatedButton(
onPressed: controller.load,
child: const Text('Retry'),
),
],
),
),
},
);
}
}The :final items pattern pulls the field out only in the branch where it exists. You cannot read items while handling loading, so a whole class of null checks disappears.
Distinguishing empty from loaded
An empty list is a valid data state but usually needs a different message. A guard clause on the pattern handles this without adding a fourth case:
String label(LoadState state) => switch (state) {
LoadStateLoading() => 'Loading',
LoadStateData(:final items) when items.isEmpty => 'Nothing here yet',
LoadStateData(:final items) => '${items.length} items',
LoadStateError(:final message) => 'Error: $message',
};Order matters. The compiler does not count a guarded pattern toward exhaustiveness, so the unguarded LoadStateData case must follow it. If you remove the unguarded case, the switch fails to compile, which is the safety net working.
Keeping data visible during a refresh
The simple union has a flaw. Pull-to-refresh sets the state to loading, which replaces the list with a spinner and discards the items the user was reading. Two common fixes exist.
The first adds a flag to the data case, keeping the model small:
@freezed
sealed class LoadState with _$LoadState {
const factory LoadState.loading() = LoadStateLoading;
const factory LoadState.data(
List<String> items, {
@Default(false) bool isRefreshing,
}) = LoadStateData;
const factory LoadState.error(String message) = LoadStateError;
}The controller then updates the existing value with copyWith instead of replacing it:
Future<void> refresh() async {
final current = value;
if (current is LoadStateData) {
value = current.copyWith(isRefreshing: true);
} else {
value = const LoadState.loading();
}
try {
final items = await _fetch();
if (_disposed) return;
value = LoadState.data(items);
} catch (e) {
if (_disposed) return;
value = LoadState.error(e.toString());
}
}The widget can show a thin LinearProgressIndicator above the list when isRefreshing is true. The flag is legal only on data, so the model still cannot express "refreshing an error".
The second fix is to give error an optional previousItems field, so a failed refresh can show the old list with a banner. Choose it when users need to keep working offline. Each extra field makes the model closer to the flag soup you started with, so add one only when a screen needs it.
Making the union generic
Many screens share this shape, and you can parameterize the union over the payload type:
@freezed
sealed class Async<T> with _$Async<T> {
const factory Async.loading() = AsyncLoading<T>;
const factory Async.data(T value) = AsyncData<T>;
const factory Async.error(String message) = AsyncError<T>;
}Note that Flutter's dart:async and some state packages already export names like AsyncError and AsyncValue. If you hit an ambiguous import, rename the cases, for example RemoteLoading, or import with a prefix. Resist building one universal type for every screen. A screen with a distinct state, such as "needs login", is better served by its own union.
Gotchas
| Problem | Cause | Fix |
|---|---|---|
| Switch reports a missing case after adding a constructor | The compiler is doing its job | Handle the new case in every switch |
| UI does not update after mutating the list inside `data` | The list was changed in place, so the old and new states are `==` | Build a new list and assign a new state |
| `A value of type ... can't be assigned` when reading `items` | You are reading a field on the base `LoadState` | Match the case first with a pattern or `is` check |
| Exception after leaving the screen | Assigning to a disposed notifier | Track disposal as shown above |
| Spinner flashes for fast requests | `loading` is set unconditionally | Keep it, or delay showing the spinner in the widget |
Testing the transitions
Because states have value equality, a test can assert the exact sequence a controller produces:
import 'package:test/test.dart';
void main() {
test('load emits data after loading', () async {
final controller = ItemsController(() async => ['a', 'b']);
final seen = <LoadState>[];
controller.addListener(() => seen.add(controller.value));
await controller.load();
expect(controller.value, const LoadState.data(['a', 'b']));
controller.dispose();
});
test('load reports errors', () async {
final controller = ItemsController(() async => throw Exception('boom'));
await controller.load();
expect(controller.value, isA<LoadStateError>());
controller.dispose();
});
}The first assertion compares a whole state object against a const expectation. Without generated equality you would extract and compare each field separately.
Exercise
A screen uses the three-case LoadState. Users complain that pull-to-refresh makes the list vanish and flash a spinner. Describe one change to the model and one change to the controller that keeps the list visible while refreshing.
Show answer
Add an optional @Default(false) bool isRefreshing named parameter to the data case. In the controller's refresh method, if the current value is a LoadStateData, assign current.copyWith(isRefreshing: true) instead of LoadState.loading(). After the fetch, assign a new LoadState.data(items), which resets the flag. The widget can show a small progress bar when isRefreshing is true.
Exercise
You add a fourth case, LoadState.unauthorized(), to the union. What happens to the existing switch (state) in your widgets, and why is that useful?
Show answer
Each switch without a default branch stops compiling because it no longer covers every subtype of the sealed class. The compiler lists the missing case, so you find and update every place that must handle the new state instead of discovering the gap at runtime.