Sub topic 15
Wrapping Actions in Command Objects
Assume you know Dart classes, Future, async/await, Flutter widgets, and ChangeNotifier. This chapter builds on a view model that already exposes state and uses a repository for data access.
A view model method such as toggle(todo) is an action. As an application grows, actions often need the same extra behavior:
- Track whether the action is running.
- Store an error from the last attempt.
- Prevent duplicate taps.
- Expose a result to the view.
- Notify listeners when the action changes.
A command object packages this behavior. It represents an operation that the user can start and that has observable state.
A reusable command
The following command stores whether it is running and the most recent error. It accepts an asynchronous function when it is created.
import 'package:flutter/foundation.dart';
class AsyncCommand<T> extends ChangeNotifier {
AsyncCommand(this._action);
final Future<T> Function() _action;
bool _isRunning = false;
Object? _error;
T? _result;
bool get isRunning => _isRunning;
Object? get error => _error;
T? get result => _result;
Future<void> execute() async {
if (_isRunning) return;
_isRunning = true;
_error = null;
notifyListeners();
try {
_result = await _action();
} catch (error) {
_error = error;
} finally {
_isRunning = false;
notifyListeners();
}
}
}The guard at the beginning makes repeated taps harmless while the operation is running. The command clears the previous error before starting. It then records either the result or the error and notifies listeners after each state transition.
A command should not contain widget code. Its action can call a repository, validate input, or coordinate several domain operations.
Using a command in a view model
The view model creates a command and supplies the repository operation through a closure.
class TodoListViewModel extends ChangeNotifier {
TodoListViewModel({required TodoRepository repository})
: _repository = repository {
refresh = AsyncCommand<List<Todo>>(_loadTodos);
}
final TodoRepository _repository;
late final AsyncCommand<List<Todo>> refresh;
List<Todo> _todos = const [];
List<Todo> get todos => _todos;
Future<List<Todo>> _loadTodos() async {
final loadedTodos = await _repository.fetchTodos();
_todos = loadedTodos;
notifyListeners();
return loadedTodos;
}
@override
void dispose() {
refresh.dispose();
super.dispose();
}
}The view can listen to the view model and inspect refresh.isRunning or refresh.error. It can disable a refresh button while the command is running.
ListenableBuilder(
listenable: vm,
builder: (context, _) {
return ElevatedButton(
onPressed: vm.refresh.isRunning ? null : vm.refresh.execute,
child: Text(vm.refresh.isRunning ? 'Loading...' : 'Refresh'),
);
},
)Choosing commands carefully
Commands are useful when an action has meaningful lifecycle state. They can reduce repeated loading and error code across a view model. They also make the view’s intent clear: the button executes a command.
A command adds another object and another disposal responsibility. For a one-line synchronous action, a normal view-model method is simpler. Use commands when the shared behavior is valuable, rather than wrapping every method automatically.
Exercise
Why should execute return immediately when the command is already running?
Show answer
It prevents duplicate requests caused by repeated taps and keeps one command instance responsible for one active operation.