Sub topic 3
Structuring an API client class
This chapter assumes you know Dart classes, null safety, async/await, basic StatefulWidget use, and how to add a package to pubspec.yaml.
Structuring an API client class
Keep all HTTP calls in one class. The widgets then call methods such as fetchPost and never build URLs themselves. Pass the http.Client in through the constructor so tests can replace it.
import 'dart:convert';
import 'package:http/http.dart' as http;
class ApiException implements Exception {
const ApiException(this.message, {this.statusCode});
final String message;
final int? statusCode;
}
class Post {
const Post({required this.id, required this.title});
factory Post.fromJson(Map<String, dynamic> json) =>
Post(id: json['id'] as int, title: json['title'] as String);
final int id;
final String title;
}
class PostApi {
PostApi(this._client);
final http.Client _client;
Future<Post> fetchPost(int id) async {
final uri = Uri.https('jsonplaceholder.typicode.com', '/posts/$id');
final response = await _client.get(uri);
if (response.statusCode != 200) {
throw ApiException('Failed to load post', statusCode: response.statusCode);
}
return Post.fromJson(jsonDecode(response.body) as Map<String, dynamic>);
}
}Loading, data and error states with FutureBuilder
Create the future once in initState. A FutureBuilder then shows a spinner while the request runs, an error message on failure, and the data on success.
Testing API code without a network
MockClient from package:http/testing.dart returns a canned response. Pass it to PostApi and check the parsed result.
Parsing large responses in a background isolate
jsonDecode on a large body can drop frames. compute runs a top-level function in a separate isolate, so the UI thread stays free.
final posts = await compute(parsePosts, response.body);Dio as an alternative to http
Dio adds a base URL, timeouts, automatic JSON decoding and interceptors. The http package is smaller and enough for simple apps.
| Feature | http | Dio |
|---|---|---|
| Base URL and timeouts | Manual | Built in |
| Interceptors | Not provided | Built in |
Interceptors for logging, auth and retries
An interceptor runs on every request. This one adds an Authorization header to each call.
dio.interceptors.add(
InterceptorsWrapper(
onRequest: (options, handler) {
options.headers['Authorization'] = 'Bearer $token';
handler.next(options);
},
),
);Exercise
Why does PostApi take an http.Client through its constructor instead of creating one inside fetchPost?
Show answer
The caller can pass a MockClient in tests, so the code runs without a network, and the app can reuse one client.