Sub topic 13
Dio as an alternative to http
This chapter assumes you have finished the earlier chapters. You should be comfortable with Future, async/await, the http package, the Post model, and the ApiException type from the error handling chapter. Here you will rebuild the same requests with Dio, a third-party HTTP client. You will also learn when the extra dependency is worth it.
What Dio adds
The http package is small on purpose. It sends requests and returns a Response whose body you decode yourself. Dio covers the same ground and adds features that you would otherwise write by hand.
- A base URL and default headers set once in
BaseOptions. - Separate connect, send and receive timeouts.
- Automatic JSON encoding of request bodies and decoding of response bodies.
- Cancellation with
CancelToken. - Upload and download progress callbacks.
- Interceptors, which are hooks that run on every request, response or error. The next chapter covers them.
Dio also has a cost. It is a larger dependency, it has its own exception type, and it has no MockClient equivalent. For an app with a handful of endpoints, http is often enough.
Add the package from your project folder:
flutter pub add dioA GET request with Dio
You create one Dio instance and reuse it. Settings that you would repeat in every http call go into BaseOptions.
The listing below is a complete program. It defines the Post and ApiException types again so that it runs on its own.
import 'package:dio/dio.dart';
class ApiException implements Exception {
const ApiException(this.message, {this.statusCode});
final String message;
final int? statusCode;
@override
String toString() => 'ApiException($statusCode): $message';
}
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;
}
final dio = Dio(
BaseOptions(
baseUrl: 'https://jsonplaceholder.typicode.com',
connectTimeout: const Duration(seconds: 5),
receiveTimeout: const Duration(seconds: 10),
),
);
Future<Post> fetchPostWithDio(int id) async {
try {
final response = await dio.get<Map<String, dynamic>>('/posts/$id');
return Post.fromJson(response.data!);
} on DioException catch (e) {
throw ApiException(
e.message ?? 'Request failed',
statusCode: e.response?.statusCode,
);
}
}
Future<void> main() async {
final post = await fetchPostWithDio(1);
print(post.title);
}Compare this with the http version:
- You pass a path (
'/posts/$id'), not aUri. Dio joins it tobaseUrl. - You never call
jsonDecode. When the response has a JSON content type,response.datais already a decodedMaporList. - The type argument in
dio.get<Map<String, dynamic>>tells Dart whatdatashould be. If the server returns a list, that type is wrong and you get a cast error at runtime. Usedio.get<List<dynamic>>for list endpoints. - You do not check
statusCode != 200. By default, Dio throws for any status outside 200 to 299.
Sending data
For a POST you pass a Map as data. Dio encodes it as JSON and sets Content-Type: application/json for you.
Future<Post> createPostWithDio(String title) async {
try {
final response = await dio.post<Map<String, dynamic>>(
'/posts',
data: {'title': title},
);
if (response.statusCode != 201) {
throw ApiException(
'Unexpected status',
statusCode: response.statusCode,
);
}
return Post.fromJson(response.data!);
} on DioException catch (e) {
throw ApiException(
e.message ?? 'Request failed',
statusCode: e.response?.statusCode,
);
}
}The 201 Created check is still useful. Dio accepts every 2xx status, so a server that returns 200 where you expected 201 would pass without it. Whether that matters depends on the API. put, patch and delete work the same way.
How Dio reports errors
Dio throws a single exception type, DioException. Its type field says what went wrong. This replaces the mix of TimeoutException, ClientException and manual status checks in the http version.
| `DioExceptionType` | Meaning |
|---|---|
| `connectionTimeout` | The connection was not established within `connectTimeout`. |
| `sendTimeout` | Sending the request body took longer than `sendTimeout`. |
| `receiveTimeout` | The gap between received data exceeded `receiveTimeout`. |
| `badResponse` | The server answered with a status that `validateStatus` rejected. |
| `connectionError` | The network was unreachable or the host could not be resolved. |
| `badCertificate` | The TLS certificate was rejected. |
| `cancel` | The request was cancelled with a `CancelToken`. |
| `unknown` | Anything else, with the original error in `e.error`. |
You can map these to the same ApiException your UI already handles:
ApiException mapDioException(DioException e) {
switch (e.type) {
case DioExceptionType.connectionTimeout:
case DioExceptionType.sendTimeout:
case DioExceptionType.receiveTimeout:
return const ApiException('The request timed out');
case DioExceptionType.badResponse:
return ApiException(
'Request failed',
statusCode: e.response?.statusCode,
);
case DioExceptionType.connectionError:
return ApiException('Connection problem: ${e.message}');
case DioExceptionType.cancel:
return const ApiException('The request was cancelled');
default:
return ApiException(e.message ?? 'Unexpected error');
}
}With this helper, each method needs one catch clause: on DioException catch (e) { throw mapDioException(e); }.
Differences that cause bugs
Timeouts are not the same thing
With http, you wrapped the whole call in Future.timeout, so the limit covered the entire exchange. Dio splits the limit into phases. A download that keeps sending bytes slowly will never trigger receiveTimeout, because it measures the gap between data events and not the total time. If you need a hard overall limit, wrap the call in Future.timeout as before, or use a CancelToken with a timer.
Status handling is configurable
validateStatus decides which statuses count as success. Some teams change it so that 404 does not throw and the code can treat "not found" as a normal result:
final lenient = Dio(
BaseOptions(
baseUrl: 'https://jsonplaceholder.typicode.com',
validateStatus: (status) => status != null && status < 500,
),
);If you do this, you must check response.statusCode yourself, or a 401 will look like a successful response. Keep the default unless you have a specific reason to change it.
`response.data` can be null or the wrong type
data is dynamic underneath. The ! in response.data! fails on an empty body such as a 204 No Content. A mismatch between the declared type and the real JSON shape fails when you read the value, not when you make the call. Treat data like any untrusted input.
Cancelling requests
A CancelToken stops a request that is no longer needed, for example when the user leaves a screen:
final token = CancelToken();
Future<Post> fetchCancellable(int id) async {
try {
final response = await dio.get<Map<String, dynamic>>(
'/posts/$id',
cancelToken: token,
);
return Post.fromJson(response.data!);
} on DioException catch (e) {
throw mapDioException(e);
}
}
void onScreenClosed() => token.cancel('Screen closed');A token can only be cancelled once. Create a new one for each logical request, or each screen.
Fitting Dio into your API client
Pass the Dio instance into your API client through the constructor, the same way you passed http.Client:
class PostApi {
PostApi(this._dio);
final Dio _dio;
Future<Post> fetch(int id) async {
try {
final response = await _dio.get<Map<String, dynamic>>('/posts/$id');
return Post.fromJson(response.data!);
} on DioException catch (e) {
throw mapDioException(e);
}
}
}The rest of the app depends on PostApi and ApiException, not on Dio. This keeps the choice of HTTP library inside one class, so you can switch later without touching widgets.
Testing
MockClient belongs to the http package and does not work with Dio. You have two options. You can put your own interface in front of PostApi and fake it in widget tests. Or you can replace Dio's httpClientAdapter with a test adapter, for example from the http_mock_adapter package. The first option needs no extra dependency.
Choosing between http and Dio
| Situation | Better fit |
|---|---|
| A few simple endpoints, small app | `http` |
| You want the smallest dependency and the `MockClient` testing path | `http` |
| Many endpoints sharing a base URL, headers and timeouts | Dio |
| Upload or download progress, or request cancellation | Dio |
| Cross-cutting behavior such as logging, token refresh and retries | Dio, with interceptors |
Exercise
A Dio call to /posts/9999 returns HTTP 404. With default settings, what does your await dio.get(...) do, and which DioExceptionType do you see?
Show answer
The call throws a DioException instead of returning a Response, because the default validateStatus accepts only statuses from 200 to 299. The exception's type is DioExceptionType.badResponse, and e.response?.statusCode is 404.
Exercise
A download sends one byte every 8 seconds for five minutes, and receiveTimeout is 10 seconds. Does the request time out? How would you enforce a 60-second limit for the whole request?
Show answer
It does not time out. receiveTimeout measures the gap between received data events, and each gap here is 8 seconds. To enforce a total limit, wrap the call in Future.timeout(const Duration(seconds: 60)), or start a 60-second timer that calls token.cancel() on a CancelToken passed to the request.