Sub topic 10
Modeling Loading and Error States
This chapter assumes you know basic Dart classes, async/await, Future, and Flutter widget lifecycle methods. It also assumes you have used setState and understand why view state becomes harder to manage as a widget grows.
A view model must describe more than successful data. A request can be running, complete, or failed. If the view model exposes only a list, the view cannot reliably decide whether to show a spinner, an empty state, or an error message.
Represent the request lifecycle
A simple view model commonly stores three pieces of UI state:
- The current data, such as a list of todos.
- An
isLoadingflag. - An
errorvalue, which isnullwhen no error is present.
These values describe a small state machine:
The important rule is that every state transition must notify listeners. A view that is listening to the view model then rebuilds with the correct screen.
Use `try`, `catch`, and `finally`
Put the asynchronous repository call inside try. Store the failure in catch, and reset the loading flag in finally. The finally block runs after both success and failure, so the spinner cannot remain visible accidentally.
import 'package:flutter/foundation.dart';
abstract class TodoRepository {
Future<List<String>> fetchTodos();
}
class TodoListViewModel extends ChangeNotifier {
TodoListViewModel({required TodoRepository repository})
: _repository = repository;
final TodoRepository _repository;
List<String> _todos = const [];
bool _isLoading = false;
Object? _error;
List<String> get todos => List.unmodifiable(_todos);
bool get isLoading => _isLoading;
Object? get error => _error;
Future<void> load() async {
_isLoading = true;
_error = null;
notifyListeners();
try {
_todos = await _repository.fetchTodos();
} catch (exception) {
_error = exception;
} finally {
_isLoading = false;
notifyListeners();
}
}
}The getters expose read-only views of the state. Callers can read the list but cannot replace or mutate the view model's private list through todos.
Decide what happens to old data
When a refresh fails, you can clear the old data or keep it visible. Keeping old data is often better because the user can still see the last successful result. The view can show an error banner above that data and offer a retry action.
Clear _error before each new request. Otherwise, a previous error may remain visible during a later successful load.
Render each state in the view
A ListenableBuilder can map view-model state to widgets:
ListenableBuilder(
listenable: viewModel,
builder: (context, _) {
if (viewModel.isLoading) {
return const Center(child: CircularProgressIndicator());
}
if (viewModel.error != null && viewModel.todos.isEmpty) {
return Center(
child: Text('Could not load todos: ${viewModel.error}'),
);
}
return ListView(
children: [
if (viewModel.error != null)
const ListTile(title: Text('Refresh failed')),
for (final todo in viewModel.todos) ListTile(title: Text(todo)),
],
);
},
)This ordering gives loading priority, shows a full-page error when no data exists, and preserves old data when a refresh fails.
Exercise
Why should the loading flag be reset in a finally block?
Show answer
A finally block runs after both successful and failed requests, so the view model cannot leave the progress indicator active after an exception.