Sub topic 2
Services: wrapping APIs and storage
This chapter assumes you know Dart classes, async/await with Futures, and how a StatefulWidget builds its UI. It covers the layers that move data from an API or local storage into a view model.
Services as data sources
A service is a class that talks to one external source, such as an HTTP API or local storage. It returns raw data and hides the details of that source. Keep services thin. They should not cache results or hold UI state.
class TodoApiService {
Future<List<Map<String, dynamic>>> fetchTodoJson() async {
// Stand-in for an HTTP call.
await Future<void>.delayed(const Duration(milliseconds: 300));
return [
{'id': 1, 'title': 'Write the view model', 'done': false},
{'id': 2, 'title': 'Connect the view', 'done': true},
];
}
}Repositories as the single source of truth
A repository sits above services. It converts raw data into typed models and decides where the data comes from. The view model depends on the repository, not on the service.
class Todo {
const Todo({required this.id, required this.title, this.done = false});
final int id;
final String title;
final bool done;
factory Todo.fromJson(Map<String, dynamic> json) => Todo(
id: json['id'] as int,
title: json['title'] as String,
done: json['done'] as bool,
);
}
class TodoRepository {
TodoRepository(this._api);
final TodoApiService _api;
Future<List<Todo>> fetchTodos() async {
final json = await _api.fetchTodoJson();
return json.map(Todo.fromJson).toList();
}
}Building a view model on ChangeNotifier
A view model extends ChangeNotifier, holds private state, and exposes read-only getters. It calls notifyListeners() after every state change.
import 'package:flutter/foundation.dart';
class TodoListViewModel extends ChangeNotifier {
TodoListViewModel({required TodoRepository repository})
: _repository = repository;
final TodoRepository _repository;
List<Todo> _todos = const [];
bool _isLoading = false;
Object? _error;
List<Todo> get todos => _todos;
bool get isLoading => _isLoading;
Object? get error => _error;
Future<void> load() async {
_isLoading = true;
_error = null;
notifyListeners();
try {
_todos = await _repository.fetchTodos();
} catch (e) {
_error = e;
} finally {
_isLoading = false;
notifyListeners();
}
}
}Rebuilding the view with ListenableBuilder and Provider
ListenableBuilder rebuilds its child whenever the listenable notifies. The view only reads state and forwards user actions to the view model.
import 'package:flutter/material.dart';
class TodoScreen extends StatelessWidget {
const TodoScreen({super.key, required this.viewModel});
final TodoListViewModel viewModel;
@override
Widget build(BuildContext context) {
return ListenableBuilder(
listenable: viewModel,
builder: (context, _) {
if (viewModel.isLoading) {
return const Center(child: CircularProgressIndicator());
}
if (viewModel.error != null) {
return Center(child: Text('Error: ${viewModel.error}'));
}
return ListView(
children: [
for (final todo in viewModel.todos) ListTile(title: Text(todo.title)),
],
);
},
);
}
}The provider package offers the same rebuild behavior through ChangeNotifierProvider and Consumer. It also creates and disposes the view model for you.
Modeling loading and error states
Each load moves the view model through three states:
| State | isLoading | error | todos |
|---|---|---|---|
| Loading | true | null | previous list |
| Failed | false | set | previous list |
| Loaded | false | null | new list |
Exercise
In load(), why does finally call notifyListeners() even when the repository throws?
Show answer
The finally block runs on both success and failure. Without it, a failed load would leave isLoading set to true, and the view would show a spinner forever. Calling notifyListeners() there tells the view to rebuild with the final state.