HTTP Client, Dio & Interceptor Pipelines
Build production-grade mobile networking layers: compare http vs. Dio, configure base options, implement automatic JWT token refresh mutex locks in Interceptors, and support upload progress.
1. Mobile HTTP Networking: package:http vs. Dio
| Feature Capability | package:http (Official) | Dio (Enterprise Standard) |
|---|---|---|
| Philosophy | Minimalist, low-level HTTP wrapper | Feature-rich, production-oriented client |
| Interceptors | ❌ Manual wrapping required | ✅ Built-in (onRequest, onResponse, onError) |
| Global Base URL & Config | ❌ Per-request setup | ✅ Centralized BaseOptions |
| Token Refresh & Replay | ❌ Complex custom logic | ✅ Native request queuing & locking |
| File Upload / Download Progress | ❌ Manual stream calculation | ✅ Built-in onSendProgress & onReceiveProgress |
| Request Cancellation | ❌ Not supported | ✅ CancelToken support |
2. Setting Up a Production Dio Client
import 'package:dio/dio.dart';
class ApiClient {
late final Dio dio;
ApiClient({required String baseUrl}) {
dio = Dio(
BaseOptions(
baseUrl: baseUrl,
connectTimeout: const Duration(seconds: 10),
receiveTimeout: const Duration(seconds: 15),
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
),
);
// Register interceptor chain
dio.interceptors.addAll([
AuthInterceptor(dio: dio),
LogInterceptor(requestBody: true, responseBody: true),
]);
}
}3. JWT Token Refresh Interceptor with Request Replay
When an access token expires, a mobile app receives an HTTP 401 Unauthorized. The networking layer should pause outgoing requests, refresh the token once, update the authorization header, and transparently replay the original request:
Complete Token Refresh Interceptor Code
class AuthInterceptor extends QueuedInterceptor {
final Dio dio;
AuthInterceptor({required this.dio});
@override
void onRequest(RequestOptions options, RequestInterceptorHandler handler) async {
final token = await SecureTokenStore.getAccessToken();
if (token != null) {
options.headers['Authorization'] = 'Bearer $token';
}
handler.next(options); // Continue request
}
@override
void onError(DioException err, ErrorInterceptorHandler handler) async {
// Check if error is 401 Unauthorized
if (err.response?.statusCode == 401) {
try {
final refreshToken = await SecureTokenStore.getRefreshToken();
if (refreshToken == null) {
return handler.next(err);
}
// Call auth endpoint with a raw, non-intercepted Dio instance
final refreshResponse = await Dio().post(
'https://api.example.com/v1/auth/refresh',
data: {'refreshToken': refreshToken},
);
final newAccessToken = refreshResponse.data['accessToken'];
await SecureTokenStore.saveAccessToken(newAccessToken);
// Update original request headers and replay request
final options = err.requestOptions;
options.headers['Authorization'] = 'Bearer $newAccessToken';
final clonedResponse = await dio.fetch(options);
return handler.resolve(clonedResponse); // Return successful replay to caller!
} catch (e) {
// Refresh failed: Force user logout
await SecureTokenStore.clearAll();
return handler.next(err);
}
}
handler.next(err);
}
}4. File Uploads with Progress Tracking
Future<void> uploadAvatar(String filePath, void Function(int, int) onProgress) async {
final formData = FormData.fromMap({
'avatar': await MultipartFile.fromFile(filePath, filename: 'profile.jpg'),
'userId': 'usr_9021',
});
await dio.post(
'/users/avatar',
data: formData,
onSendProgress: (int sentBytes, int totalBytes) {
final double progress = sentBytes / totalBytes;
print("Upload progress: ${(progress * 100).toStringAsFixed(1)}%");
onProgress(sentBytes, totalBytes);
},
);
}❓ Knowledge Check
Why does AuthInterceptor extend QueuedInterceptor rather than standard Interceptor in Dio?
What is the purpose of CancelToken in Dio?
Futures, Streams & Reactive UI Builders
Master asynchronous state in Flutter UI: Future vs. Stream architectures, AsyncSnapshot state handling, StreamControllers, and avoiding the fatal FutureBuilder build-loop memory bug.
JSON Serialization & Data Models
Master serialization in Flutter without reflection: manual fromJson/toJson contracts, automated json_serializable code-gen, and immutable value objects with Freezed.