Sub topic 8
Building a view model on ChangeNotifier
This chapter assumes basic Dart classes, async and await, Flutter widget lifecycle methods, and setState. A view model is a class that prepares state for a view and performs actions requested by that view. It keeps business logic out of widget code.
ChangeNotifier is a Flutter class that lets an object notify listeners when its state changes. A widget can listen to the view model and rebuild when notifyListeners() runs.
Define the view model's state
The view model should expose only the information the UI needs:
todoscontains the current data.isLoadingtells the view to show progress.errorcontains a failure, if one occurred.
Keep mutable fields private. Expose getters instead. Return an unmodifiable list so callers cannot change the view model's state directly.
import 'package:flutter/foundation.dart';
class Todo {
const Todo({
required this.id,
required this.title,
this.done = false,
});
final int id;
final String title;
final bool done;
Todo copyWith({bool? done}) {
return Todo(
id: id,
title: title,
done: done ?? this.done,
);
}
}
abstract class TodoRepository {
Future<List<Todo>> fetchTodos();
Future<void> setDone(int id, bool done);
}
class TodoListViewModel extends ChangeNotifier {
TodoListViewModel({required TodoRepository repository})
: _repository = repository;
final TodoRepository _repository;
List<Todo> _todos = const [];
bool _isLoading = false;
Object? _error;
bool _disposed = false;
List<Todo> get todos => List.unmodifiable(_todos);
bool get isLoading => _isLoading;
Object? get error => _error;
Future<void> load() async {
if (_disposed) return;
_isLoading = true;
_error = null;
notifyListeners();
try {
final result = await _repository.fetchTodos();
if (_disposed) return;
_todos = result;
} catch (exception) {
if (_disposed) return;
_error = exception;
} finally {
if (_disposed) return;
_isLoading = false;
notifyListeners();
}
}
Future<void> toggle(Todo todo) async {
try {
await _repository.setDone(todo.id, !todo.done);
final result = await _repository.fetchTodos();
if (_disposed) return;
_todos = result;
_error = null;
} catch (exception) {
if (_disposed) return;
_error = exception;
}
if (!_disposed) notifyListeners();
}
@override
void dispose() {
_disposed = true;
super.dispose();
}
}The repository is injected through the constructor. The view model does not know whether the data comes from memory, an HTTP service, or a database.
Load data and report failures
load() changes the loading state before starting asynchronous work. It clears an old error, fetches data, then stores either the result or the exception. The finally block clears the loading flag whether the request succeeds or fails.
The _disposed checks protect against a common lifecycle error. A request can finish after the screen has been removed. In that case, calling notifyListeners() on a disposed notifier is unsafe.
Follow the one-way flow
The view sends an action to the view model, such as toggle(todo). The view model updates the repository, refreshes its state, and notifies listeners. The view then rebuilds from the new getters.
This direction keeps the widget simple and makes the view model testable without rendering a Flutter screen.
Exercise
Why should the view model call notifyListeners after changing isLoading?
Show answer
Listening widgets need a notification so they can rebuild and show or hide their loading indicator.