Sub topic 6
Services: wrapping APIs and storage
This chapter assumes you have read the earlier chapters on layered architecture, immutable data models, and the Todo and TodoRepository types. You should also be comfortable with async/await and with catching exceptions in Dart. The examples use the http and shared_preferences packages, so add both to pubspec.yaml.
What a service is
A service is a class that wraps one external data source and does nothing else. Typical sources are an HTTP API, a local database, the file system, or key-value storage on the device. The service hides the details of the source (URLs, headers, status codes, storage keys) behind a few Dart methods.
A service does not know about view models, widgets, or ChangeNotifier. It also does not decide what the app does with the data. It only answers "how do I talk to this one thing?"
Services return raw data in the shape the source uses, such as decoded JSON maps. The repository turns that raw data into domain models like Todo.
| Concern | Service | Repository |
|---|---|---|
| Talks to | One external source | One or more services |
| Returns | Raw data (maps, bytes, strings) | Domain models (`Todo`) |
| Handles | Transport errors, status codes, serialization format | Caching, fallback, merging sources, mapping |
| Knows the app's domain | No | Yes |
Where services sit
The view model never calls a service directly. It asks the repository, and the repository decides which services to use.
This split pays off in two places. You can replace a service without touching the view model, for example by moving from REST to GraphQL. You can also test the repository's logic with fake services, and test each service alone against a fake HTTP client.
A service that wraps an HTTP API
The service below takes its http.Client and base URI through the constructor. That is dependency injection applied one layer lower, and it is what makes the service testable.
import 'dart:convert';
import 'package:http/http.dart' as http;
class ApiException implements Exception {
ApiException(this.statusCode, this.message);
final int statusCode;
final String message;
@override
String toString() => 'ApiException($statusCode): $message';
}
class TodoApiService {
TodoApiService({required http.Client client, required Uri baseUri})
: _client = client,
_baseUri = baseUri;
final http.Client _client;
final Uri _baseUri;
Future<List<Map<String, dynamic>>> getTodos() async {
final response = await _client
.get(_baseUri.resolve('todos'))
.timeout(const Duration(seconds: 10));
if (response.statusCode != 200) {
throw ApiException(response.statusCode, 'Could not load todos');
}
final body = jsonDecode(response.body) as List<dynamic>;
return body.cast<Map<String, dynamic>>();
}
Future<void> patchDone(int id, bool done) async {
final response = await _client.patch(
_baseUri.resolve('todos/$id'),
headers: {'Content-Type': 'application/json'},
body: jsonEncode({'done': done}),
);
if (response.statusCode != 200 && response.statusCode != 204) {
throw ApiException(response.statusCode, 'Could not update todo $id');
}
}
}Three design choices matter here.
- Status codes become exceptions. Callers get a typed
ApiExceptioninstead of having to inspect aResponse. No layer above the service needs to know about HTTP. - The timeout is explicit. Without one, a stalled connection leaves the view model in its loading state indefinitely.
- The service returns maps, not
Todoobjects. The wire format stays inside the data layer's lower half, and the repository owns the mapping.
A service that wraps local storage
Storage deserves its own service for the same reason. Key names, encoding, and versioning are details that should live in one place.
import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
class TodoCacheService {
TodoCacheService(this._prefs);
final SharedPreferences _prefs;
static const _key = 'todos_cache_v1';
Future<void> write(List<Map<String, dynamic>> todos) async {
await _prefs.setString(_key, jsonEncode(todos));
}
List<Map<String, dynamic>>? read() {
final raw = _prefs.getString(_key);
if (raw == null) return null;
try {
return (jsonDecode(raw) as List<dynamic>).cast<Map<String, dynamic>>();
} on FormatException {
return null;
}
}
}The _v1 suffix in the key is deliberate. If a later app version changes the stored shape, you can bump the suffix and old data is ignored. Corrupt data returns null instead of crashing, so a bad cache looks the same as an empty one.
SharedPreferences is created with await SharedPreferences.getInstance(). Do that once at startup and pass the instance in. A constructor that needs an await is awkward, so keep the asynchronous setup outside the service.
Combining services in a repository
The repository below implements the TodoRepository interface from earlier. It prefers the network and falls back to the cache when the network fails.
class ApiTodoRepository implements TodoRepository {
ApiTodoRepository({
required TodoApiService api,
required TodoCacheService cache,
}) : _api = api,
_cache = cache;
final TodoApiService _api;
final TodoCacheService _cache;
@override
Future<List<Todo>> fetchTodos() async {
List<Map<String, dynamic>> json;
try {
json = await _api.getTodos();
} on Exception {
final cached = _cache.read();
if (cached == null) rethrow;
return cached.map(_fromJson).toList();
}
await _cache.write(json);
return json.map(_fromJson).toList();
}
@override
Future<void> setDone(int id, bool done) => _api.patchDone(id, done);
Todo _fromJson(Map<String, dynamic> json) => Todo(
id: json['id'] as int,
title: json['title'] as String,
done: json['done'] as bool? ?? false,
);
}The view model from earlier chapters works with this class unchanged, because it only knows the TodoRepository interface. If both the network and the cache fail, the original exception is rethrown and reaches the view model's error state.
The catch clause covers only the network call, not the cache write. If a cache write fails, the user still gets fresh data, and the error is not mistaken for a network failure.
One gap remains. After setDone succeeds, the cache still holds the old done value until the next successful fetch. The view model in this tutorial refetches after each toggle, which refreshes the cache. If yours did not, you would have to update the cache inside setDone.
Testing a service
Because the client is injected, you can test the service with MockClient and no real network.
import 'package:flutter_test/flutter_test.dart';
import 'package:http/http.dart' as http;
import 'package:http/testing.dart';
void main() {
final baseUri = Uri.parse('https://example.com/api/');
test('getTodos returns decoded maps', () async {
final client = MockClient((request) async {
expect(request.url.toString(), 'https://example.com/api/todos');
return http.Response('[{"id": 1, "title": "A", "done": false}]', 200);
});
final service = TodoApiService(client: client, baseUri: baseUri);
final todos = await service.getTodos();
expect(todos.single['title'], 'A');
});
test('getTodos throws ApiException on a server error', () {
final client = MockClient((request) async => http.Response('boom', 500));
final service = TodoApiService(client: client, baseUri: baseUri);
expect(service.getTodos(), throwsA(isA<ApiException>()));
});
}Common errors
- Business rules in the service. If a service decides which todos are "overdue", the rule is now tied to one data source. Keep services mechanical and put rules in the repository or view model.
- Returning
http.Responseupward. Every caller then has to learn status codes. Convert them to exceptions inside the service. - Creating the client inside the service.
http.Client()in a field initializer makes the service impossible to test without a network, and the client is never closed. - Unchecked casts on JSON.
json['id'] as intthrows aTypeErrorif the server sends a string.TypeErroris anError, not anException, so the repository'son Exceptionclause will not catch it. Decide whether bad data should crash loudly, as it does here, or be wrapped in aFormatException. - One giant service. A class named
ApiServicewith forty methods is hard to fake. Prefer one service per resource or data source.
Exercise
In ApiTodoRepository.fetchTodos, why does the on Exception clause wrap only the _api.getTodos() call and not the _cache.write(json) call as well?
Show answer
If the write were inside the same try block, a failure while saving to storage would be treated as a network failure. The repository would then return stale cached data, or throw, even though the server responded with fresh data. Keeping the write outside means a cache problem does not discard good data or hide its cause.
Exercise
You want to add a test that proves ApiTodoRepository returns cached todos when the network fails. Which parts do you replace with fakes, and which parts of the real code do you keep?
Show answer
Replace the services. Use a fake or MockClient-backed TodoApiService that throws, and a cache backed by SharedPreferences.setMockInitialValues containing saved JSON. Keep the real ApiTodoRepository, because its fallback logic is what the test checks.