Sub topic 15
Wrapping actions in command objects
This chapter assumes you have read the earlier chapters. You should know how a view model built on ChangeNotifier exposes state, how loading and error flags work, and how a view rebuilds with ListenableBuilder. Here you will replace the hand-written flags with a small reusable class.
The problem: repeated boilerplate
In the earlier view model, load() sets _isLoading, clears _error, calls notifyListeners, runs the repository call inside try/catch/finally, and notifies again. toggle() repeats most of this with slightly different rules. Add delete, add, and rename, and you have three problems:
- Duplicated code. Every action repeats the same flag handling, so each one is another place to forget a
finally. - Shared flags. One
isLoadingboolean cannot say whether the list is loading or one row is saving. A second action overwrites the first one's state. - Double taps. Nothing stops a user from starting the same action twice while the first call is still running.
A command is an object that wraps one action and owns that action's running and error state. The view model exposes commands instead of methods plus flags.
What a command holds
A command has a function to run, and it tracks three things: whether it is running, whether the last run failed, and the last result. It extends ChangeNotifier, so a view can listen to it directly.
A reusable Command class
The base class holds the shared state and the run logic. Two small subclasses differ only in the number of arguments the action takes.
import 'package:flutter/foundation.dart';
abstract class Command<T> extends ChangeNotifier {
bool _running = false;
bool _disposed = false;
Object? _error;
T? _result;
bool get running => _running;
bool get hasError => _error != null;
Object? get error => _error;
T? get result => _result;
Future<void> _run(Future<T> Function() action) async {
if (_running) return; // ignore a second tap while busy
_running = true;
_error = null;
_result = null;
_notify();
try {
_result = await action();
} catch (e) {
_error = e;
} finally {
_running = false;
_notify();
}
}
void _notify() {
if (!_disposed) notifyListeners();
}
@override
void dispose() {
_disposed = true;
super.dispose();
}
}
class Command0<T> extends Command<T> {
Command0(this._action);
final Future<T> Function() _action;
Future<void> execute() => _run(_action);
}
class Command1<A, T> extends Command<T> {
Command1(this._action);
final Future<T> Function(A argument) _action;
Future<void> execute(A argument) => _run(() => _action(argument));
}Three design choices are worth noting:
- The guard.
if (_running) return;makes the command ignore calls while it is busy. This removes the double-tap problem in one line. - Caught errors.
executecatches every exception and stores it. The returnedFuturealways completes normally, so a caller that forgetsawaitcannot cause an unhandled async error. The cost is that failures are visible only througherror. - The disposed flag. If the user leaves the screen while the action is in flight, the
finallyblock would callnotifyListenerson a disposed object. The_disposedcheck prevents that.
Using commands in a view model
The view model now holds only the data and the commands. The actions throw on failure and leave error handling to the command.
class TodoListViewModel extends ChangeNotifier {
TodoListViewModel({required TodoRepository repository})
: _repository = repository;
final TodoRepository _repository;
List<Todo> _todos = const [];
List<Todo> get todos => _todos;
late final Command0<void> load = Command0<void>(_load);
late final Command1<Todo, void> toggle = Command1<Todo, void>(_toggle);
Future<void> _load() async {
_todos = await _repository.fetchTodos();
notifyListeners();
}
Future<void> _toggle(Todo todo) async {
await _repository.setDone(todo.id, !todo.done);
_todos = await _repository.fetchTodos();
notifyListeners();
}
@override
void dispose() {
load.dispose();
toggle.dispose();
super.dispose();
}
}late final lets each field initializer refer to the instance methods _load and _toggle, which a normal field initializer cannot do. The view model owns the commands, so it must dispose them.
Listening to commands in the view
A view listens to the view model for data and to each command for progress. Listenable.merge combines several listenables into one.
import 'package:flutter/material.dart';
class TodoScreen extends StatefulWidget {
const TodoScreen({super.key, required this.viewModel});
final TodoListViewModel viewModel;
@override
State<TodoScreen> createState() => _TodoScreenState();
}
class _TodoScreenState extends State<TodoScreen> {
@override
void initState() {
super.initState();
widget.viewModel.load.execute();
}
@override
Widget build(BuildContext context) {
final vm = widget.viewModel;
return Scaffold(
appBar: AppBar(title: const Text('Todos')),
body: ListenableBuilder(
listenable: Listenable.merge([vm, vm.load, vm.toggle]),
builder: (context, _) {
if (vm.load.running) {
return const Center(child: CircularProgressIndicator());
}
if (vm.load.hasError) {
return Center(child: Text('Could not load: ${vm.load.error}'));
}
return Column(
children: [
if (vm.toggle.hasError)
MaterialBanner(
content: Text('Could not update: ${vm.toggle.error}'),
actions: const [SizedBox.shrink()],
),
Expanded(
child: ListView(
children: [
for (final todo in vm.todos)
CheckboxListTile(
title: Text(todo.title),
value: todo.done,
onChanged: vm.toggle.running
? null
: (_) => vm.toggle.execute(todo),
),
],
),
),
],
);
},
),
);
}
}Loading and saving now have separate state. A failed toggle shows a banner without replacing the list with an error message. Passing null to onChanged disables the checkbox while a toggle runs.
Comparing the two approaches
| Concern | Flags in the view model | Commands |
|---|---|---|
| State per action | One shared set of flags | Each action has its own |
| Boilerplate per action | try/catch/finally and notifications | One line to declare the command |
| Double execution | Must be guarded by hand | Guarded in the base class |
| Number of public members | Method plus flags per action | One command per action |
| Learning cost | None | One extra class to understand |
Testing commands
The commands are plain Dart objects, so you can test them without widgets. The first test checks that the view model works through its commands. The second checks the guard, using a Completer to hold the action open.
import 'dart:async';
import 'package:flutter_test/flutter_test.dart';
class ThrowingTodoRepository implements TodoRepository {
@override
Future<List<Todo>> fetchTodos() async => throw Exception('network down');
@override
Future<void> setDone(int id, bool done) async {}
}
void main() {
test('load command stores the error instead of throwing', () async {
final vm = TodoListViewModel(repository: ThrowingTodoRepository());
await vm.load.execute();
expect(vm.load.hasError, isTrue);
expect(vm.load.running, isFalse);
expect(vm.todos, isEmpty);
});
test('a command ignores execute while it is running', () async {
final gate = Completer<void>();
var calls = 0;
final command = Command0<void>(() async {
calls++;
await gate.future;
});
final first = command.execute();
await command.execute(); // returns immediately, action not started again
expect(command.running, isTrue);
gate.complete();
await first;
expect(calls, 1);
expect(command.running, isFalse);
});
}Edge cases and cautions
- Errors are stored, not rethrown. This suits UI work, because the view reads
error. If a caller needs to react to failure in code, such as navigating after a successful save, checkcommand.hasErrorafterawait command.execute(). - Results can go stale.
executeclearsresultwhen it starts. Do not keep reading an old result across runs. - Do not build a command for everything. A synchronous action, such as flipping a local filter, needs no running or error state. A plain method is simpler.
- Do not put the command in widget state. Commands belong to the view model. A command created in
buildwould be recreated on every rebuild and lose its state.
Exercise
A user double-taps a "Save" button wired to vm.save.execute(). The repository call takes two seconds. How many times does the action run, and what two things in Command._run produce that result?
Show answer
The action runs once. The first tap sets _running to true. The guard if (_running) return; makes the second call return immediately without starting the action. When the first run finishes, the finally block sets _running back to false, so a later tap can start a new run.
Exercise
Add a Command1<int, void> named remove to TodoListViewModel. Its action should call a hypothetical _repository.delete(id) and then reload the todos. List the changes needed in the view model beyond the new field and method.
Show answer
Add Future<void> delete(int id) to TodoRepository and to every implementation, including the in-memory one and the fakes. Declare late final Command1<int, void> remove = Command1<int, void>(_remove); with _remove calling await _repository.delete(id), then _todos = await _repository.fetchTodos(), then notifyListeners(). Call remove.dispose() in the view model's dispose. In the view, add vm.remove to the Listenable.merge list if the screen should react to its running or error state.