Sub topic 6
Services: Wrapping APIs and Storage
Assume you know Dart classes, Future, and basic Flutter widgets. This chapter focuses on the service layer. A service wraps one external data source, such as an HTTP API or local storage, behind a small Dart interface.
What a service does
A service translates between your application and an external system. It handles details such as:
- Building API requests.
- Decoding response data.
- Converting database rows or JSON into Dart objects.
- Saving and reading cached data.
- Translating low-level failures into useful exceptions.
A service should not decide how a screen displays loading or error state. That belongs in the view model. A service also should not contain widget code.
| Layer | Main responsibility | Example |
|---|---|---|
| View | Displays state and sends user actions | `CheckboxListTile` |
| View model | Coordinates state and actions | `TodoListViewModel` |
| Repository | Chooses and combines data sources | Remote data, then cache |
| Service | Wraps one external system | `TodoApi` or `TodoStorage` |
Wrapping remote and local data sources
The service boundary keeps external formats away from the rest of the application. For example, an API might return JSON maps, while the application uses Todo objects.
The following example uses fake implementations so it can run without a network or database:
abstract class TodoApi {
Future<List<Map<String, Object?>>> fetchTodos();
}
class FakeTodoApi implements TodoApi {
@override
Future<List<Map<String, Object?>>> fetchTodos() async {
await Future<void>.delayed(const Duration(milliseconds: 200));
return [
{'id': 1, 'title': 'Read the API response'},
{'id': 2, 'title': 'Save a local copy'},
];
}
}
abstract class TodoStorage {
Future<void> save(List<Todo> todos);
Future<List<Todo>> read();
}
class MemoryTodoStorage implements TodoStorage {
List<Todo> _todos = const [];
@override
Future<void> save(List<Todo> todos) async {
_todos = List.unmodifiable(todos);
}
@override
Future<List<Todo>> read() async => _todos;
}
class Todo {
const Todo({required this.id, required this.title});
final int id;
final String title;
@override
String toString() => '$id: $title';
}
class TodoService {
TodoService({required this.api, required this.storage});
final TodoApi api;
final TodoStorage storage;
Future<List<Todo>> loadTodos() async {
try {
final rows = await api.fetchTodos();
final todos = [
for (final row in rows)
Todo(
id: row['id'] as int,
title: row['title'] as String,
),
];
await storage.save(todos);
return todos;
} catch (_) {
return storage.read();
}
}
}
Future<void> main() async {
final service = TodoService(
api: FakeTodoApi(),
storage: MemoryTodoStorage(),
);
print(await service.loadTodos());
}The service converts API rows into immutable domain objects. It then stores the converted objects. If the API fails, it tries the cached values instead.
Service and repository responsibilities
A repository often coordinates several services. For example, TodoRepository.fetchTodos() might call TodoService.loadTodos() and expose the result to a view model. This keeps the view model independent of HTTP clients, database packages, and JSON shapes.
Keep error behavior explicit. A fallback to cached data is useful when the cache is valid, but silently returning an empty list can hide a real failure. In a production service, distinguish between an unavailable network, invalid response data, and corrupted local data.
Exercise
Why should an API service convert JSON maps into Todo objects before returning data?
Show answer
It keeps external data formats at the boundary, so repositories, view models, and widgets work with typed application objects.