What is the main advantage of Dio over the basic http package?
Dio provides interceptors for centralized request/response handling, request cancellation tokens, file upload progress tracking, and automatic JSON transformation.
Build robust API layers with Dio, interceptors, and caching
You can read this lesson publicly. Sign in to unlock exercises, quiz, and FX progress tracking.
Having trouble? AI is here to help
Ask context-aware questions about this lesson. Free plan: 5 questions/day. Upgrade to Premium for higher daily limits.
Use the AI button at the bottom of the screen
Dio is the most popular HTTP client for Flutter, offering interceptors, request cancellation, file uploads, timeout configuration, and automatic JSON transformation out of the box. While the basic http package works for simple requests, Dio provides the advanced features that production apps require, including centralized error handling, token refresh logic, and request/response logging.
1// pubspec.yaml: dio: ^5.4.02import 'package:dio/dio.dart';34// ── Basic Dio Setup ──5class ApiClient {6late final Dio _dio;78ApiClient() {9_dio = Dio(BaseOptions(10baseUrl: 'https://api.example.com/v1',11connectTimeout: const Duration(seconds: 10),12receiveTimeout: const Duration(seconds: 10),13headers: {14'Content-Type': 'application/json',15'Accept': 'application/json',16},17));1819// Add interceptors20_dio.interceptors.addAll([21LogInterceptor(requestBody: true, responseBody: true),22AuthInterceptor(),23RetryInterceptor(),24]);25}2627// GET request28Future<List<Post>> getPosts() async {29final response = await _dio.get('/posts');30return (response.data as List)31.map((json) => Post.fromJson(json))32.toList();33}3435// POST request36Future<Post> createPost(String title, String body) async {37final response = await _dio.post('/posts', data: {38'title': title,39'body': body,40});41return Post.fromJson(response.data);42}4344// PUT request with path parameter45Future<Post> updatePost(int id, Map<String, dynamic> data) async {46final response = await _dio.put('/posts/$id', data: data);47return Post.fromJson(response.data);48}4950// DELETE request51Future<void> deletePost(int id) async {52await _dio.delete('/posts/$id');53}5455// File upload with progress56Future<String> uploadImage(File file) async {57final formData = FormData.fromMap({58'image': await MultipartFile.fromFile(59file.path,60filename: 'upload.jpg',61),62});63final response = await _dio.post(64'/upload',65data: formData,66onSendProgress: (sent, total) {67print('Upload: ${(sent / total * 100).toStringAsFixed(0)}%');68},69);70return response.data['url'];71}72}
1// ── AUTH INTERCEPTOR (Token Refresh) ──2class AuthInterceptor extends Interceptor {3@override4void onRequest(RequestOptions options, RequestInterceptorHandler handler) {5final token = AuthService.instance.accessToken;6if (token != null) {7options.headers['Authorization'] = 'Bearer $token';8}9handler.next(options);10}1112@override13void onError(DioException err, ErrorInterceptorHandler handler) async {14if (err.response?.statusCode == 401) {15// Token expired: try to refresh16try {17final newToken = await AuthService.instance.refreshToken();18err.requestOptions.headers['Authorization'] = 'Bearer $newToken';1920// Retry the original request21final response = await Dio().fetch(err.requestOptions);22handler.resolve(response);23return;24} catch (_) {25AuthService.instance.logout();26}27}28handler.next(err);29}30}3132// ── CENTRALIZED ERROR HANDLING ──33class ApiException implements Exception {34final String message;35final int? statusCode;3637ApiException(this.message, {this.statusCode});3839factory ApiException.fromDioError(DioException error) {40switch (error.type) {41case DioExceptionType.connectionTimeout:42case DioExceptionType.receiveTimeout:43return ApiException('Connection timed out', statusCode: 408);44case DioExceptionType.badResponse:45final code = error.response?.statusCode;46final msg = error.response?.data?['message'] ?? 'Server error';47return ApiException(msg, statusCode: code);48case DioExceptionType.connectionError:49return ApiException('No internet connection');50default:51return ApiException('Something went wrong');52}53}54}5556// Wrap calls with error handling:57Future<Result<T>> safeApiCall<T>(Future<T> Function() call) async {58try {59final data = await call();60return Success(data);61} on DioException catch (e) {62return Failure(ApiException.fromDioError(e).message);63}64}
Interceptors run in the order they are added. Place the auth interceptor first so every request gets the token. Place logging last so it captures the final request including auth headers. For retry logic, place it after auth so retried requests also include fresh tokens.
Production API layers need consistency guarantees:
Reliable API foundations reduce cascading failures in higher app layers.
Build robust API layers with Dio, interceptors, and caching. Networking lessons teach your app how to request, store, and display remote data safely.
Operate with production and interview-level clarity.
Always model loading, success, empty, and error states before hooking the UI.
Most production bugs happen at data boundaries: slow networks, bad payloads, and error states.
Repository and service boundaries keep networking logic testable and replaceable.
As your app grows, keep UI, state, and data responsibilities separate so each part stays testable and easier to modify.
Dio provides interceptors for centralized request/response handling, request cancellation tokens, file upload progress tracking, and automatic JSON transformation.
A 401 status means the token has expired. A well-designed auth interceptor attempts to refresh the token and retry the original request transparently.
Dio uses FormData.fromMap with MultipartFile.fromFile to create multipart form uploads, similar to HTML form file uploads.
Something seems incorrect, unclear, or missing? Let us know.
FlutterCraft editorial lessons are reviewed by experienced Flutter developers and updated to stay aligned with modern Flutter and Dart best practices.
Reference docs: Flutter Documentation, Dart Language Tour, and official package documentation where relevant.
Sign in to continue with exercises and quiz for this lesson.
Sign In to Continue