Sub topic 13
Dio as an Alternative to `http`
This chapter assumes you know Dart classes, null safety, Future, async and await, basic Flutter widgets, and how to add packages to pubspec.yaml. You should also understand the request and response flow from earlier chapters.
The http package is small and explicit. You build a Uri, send a request, check the status code, and decode the response yourself. Dio is a larger HTTP client with features such as base URLs, request interceptors, timeouts, cancellation, file uploads, and automatic error objects.
Comparing `http` and Dio
Both packages can call REST endpoints. The main difference is how much networking behavior each package provides for you.
| Need | `http` | Dio |
|---|---|---|
| Basic GET and POST requests | Simple and direct | Simple, with more configuration |
| JSON decoding | Usually manual | Response data is commonly decoded automatically |
| Base URL | You manage it | Configure it once |
| Status errors | Check `statusCode` yourself | Failed statuses usually throw `DioException` |
| Interceptors | Not built in | Built in |
| Dependency size and complexity | Smaller | Larger, but more features |
Choose http when your application has a small number of endpoints and you want minimal abstraction. Choose Dio when several requests share configuration or when authentication, logging, retries, uploads, or cancellation need a common implementation.
Configure a Dio client
Add Dio to pubspec.yaml:
dependencies:
dio: ^5.7.0Create one configured client instead of constructing a new client for every request. The base URL and timeout settings then apply consistently.
import 'package:dio/dio.dart';
class Post {
const Post({required this.id, required this.title});
factory Post.fromJson(Map<String, dynamic> json) {
return 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),
headers: {'Accept': 'application/json'},
),
);
Future<Post> fetchPost(int id) async {
try {
final response = await dio.get<Map<String, dynamic>>('/posts/$id');
return Post.fromJson(response.data!);
} on DioException catch (error) {
throw Exception(
'Request failed: ${error.response?.statusCode ?? error.message}',
);
}
}Dio decodes a JSON response into Dart maps when the server returns a JSON content type. The generic type on get documents the expected response shape. You still need to validate the map and convert it into your own model.
Add query parameters and send JSON
Dio accepts query parameters separately from the path. It also encodes a Dart map as a JSON request body when the content type is JSON.
Future<Post> createPost(String title) async {
final response = await dio.post<Map<String, dynamic>>(
'/posts',
queryParameters: {'source': 'mobile'},
data: {'title': title},
options: Options(
headers: {'Content-Type': 'application/json'},
),
);
if (response.statusCode != 201) {
throw StateError('Expected 201, got ${response.statusCode}');
}
return Post.fromJson(response.data!);
}Dio can also send put, patch, and delete requests with the same method style. Use the HTTP method that matches the server contract. Do not treat a successful transport response as proof that the operation succeeded semantically. The response body and status code still matter.
Use interceptors for shared behavior
An interceptor runs around requests and responses. It is useful for adding an access token, recording safe diagnostic information, or applying shared response rules.
final dioWithAuth = Dio(
BaseOptions(baseUrl: 'https://api.example.com'),
)..interceptors.add(
InterceptorsWrapper(
onRequest: (options, handler) {
options.headers['Authorization'] = 'Bearer token-from-secure-storage';
handler.next(options);
},
onError: (error, handler) {
if (error.response?.statusCode == 401) {
// Clear the session or start a controlled sign-in flow.
}
handler.next(error);
},
),
);Keep secrets out of logs. A logging interceptor should redact authorization headers and private response data. Automatic retries also need care. Retrying a failed GET is usually safer than retrying a payment or order-creation POST unless the API supports idempotency keys.
Choose Dio deliberately
Dio is a good fit when your application needs shared authentication, upload progress, cancellation, or several cross-cutting policies. Its extra behavior also creates more configuration and more places for a bug to hide. For a small client, http may be easier to test and maintain.
Exercise
Why might an application choose Dio instead of http?
Show answer
Dio provides shared configuration and built-in features such as interceptors, typed response handling, cancellation, and upload support. The application should accept its additional dependency and configuration only when those features are useful.