Bài viết gần đây
-
-
So sánh Flutter và React Native
Tháng mười một 17, 2025 -
So sánh Flutter và React Native
Tháng mười một 17, 2025 -
Chiến lược RSI 30–70 trong Bot Auto Trading Python
Tháng mười một 17, 2025 -
Chiến Lược Giao Dịch News Filter sử dụng API Python
Tháng mười một 17, 2025
| Flutter: Sử dụng Dio để gọi API nâng cao
Được viết bởi thanhdt vào ngày 15/11/2025 lúc 08:18 | 14 lượt xem
Buổi 5: Sử dụng Dio để gọi API nâng cao
Trong buổi này, chúng ta sẽ tìm hiểu cách sử dụng thư viện Dio để gọi API trong Flutter ở mức nâng cao – bao gồm Interceptors, Timeout, Retry request và thêm Header Authorization.
1. So sánh Dio và http
| Tiêu chí | http package | dio package |
|---|---|---|
| Đơn giản | ⭐⭐⭐⭐⭐ | ⭐⭐⭐ |
| Interceptors | ❌ | ✅ |
| Timeout nâng cao | ❌ | ✅ |
| Retry request | ❌ | ✅ |
| Upload/Download tracking | ❌ | ✅ |
| Hỗ trợ FormData | Hạn chế | Rất tốt |
| Tùy chỉnh Header linh hoạt | Trung bình | Tốt |
Kết luận: App phức tạp có login/token → nên dùng Dio.
2. Cấu hình Dio Interceptors
Interceptors giúp:
- Thêm header cho mọi request
- Log request/response
- Tự động refresh token
- Retry khi gặp lỗi mạng
Ví dụ cấu hình Interceptor:
class ApiClient {
final Dio dio = Dio();
ApiClient() {
dio.options.baseUrl = "https://api.example.com";
dio.interceptors.add(
InterceptorsWrapper(
onRequest: (options, handler) {
print(" Request: ${options.method} ${options.path}");
options.headers['Authorization'] = "Bearer YOUR_TOKEN";
return handler.next(options);
},
onResponse: (response, handler) {
print(" Response: ${response.statusCode}");
return handler.next(response);
},
onError: (error, handler) {
print(" Error: ${error.message}");
return handler.next(error);
},
),
);
}
}
3. Thực hiện Request có Header & Authorization
Ví dụ gửi GET Request:
final dio = Dio();
final response = await dio.get(
"/users",
options: Options(
headers: {
"Authorization": "Bearer abc123",
"Content-Type": "application/json",
},
),
);
print(response.data);
4. Cấu hình Timeout & Retry Request
Timeout
dio.options.connectTimeout = Duration(seconds: 5);
dio.options.receiveTimeout = Duration(seconds: 5);
Retry Request đơn giản
dio.interceptors.add(
InterceptorsWrapper(
onError: (e, handler) async {
if (e.type == DioExceptionType.connectionTimeout) {
print(" Thử request lại...");
final cloneReq = await dio.request(
e.requestOptions.path,
options: Options(method: e.requestOptions.method),
);
return handler.resolve(cloneReq);
}
return handler.next(e);
},
),
);
5. Bài tập thực hành
Yêu cầu bài tập:
- Tạo lớp
ApiClientsử dụng Dio - Cấu hình Interceptor:
- Thêm Authorization Header
- Log request + response
- Gọi API GET:
https://jsonplaceholder.typicode.com/posts
- Hiển thị danh sách Post ra màn hình Flutter
- Thêm nút Refresh để gọi lại API
- (Bonus) Thêm timeout + retry request
Kết luận
Dio là thư viện mạnh nhất để gọi API trong Flutter khi dự án có:
- Login
- Token
- Kết nối API phức tạp
- Upload/Download
Hiểu được Interceptors + Timeout + Retry giúp bạn xây dựng API Client chuyên nghiệp giống như các app lớn.