Learn/Backend & Cloud/REST APIs with Dio

REST APIs with Dio

Build robust API layers with Dio, interceptors, and caching

8 min~5 min read+50 FX

You can read this lesson publicly. Sign in to unlock exercises, quiz, and FX progress tracking.

Table of Contents

  1. 1. API Client Reliability Model
  2. 2. This Lesson In Simple Words
  3. 3. Your level focus
  4. 4. One practical habit
  5. 5. Deep Understanding Guide
  6. 6. Why this lesson matters
  7. 7. Study flow for better retention
  8. 8. Quick Glossary
  9. 9. Architecture Lens

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

REST APIs with Dio

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.

dart
1// pubspec.yaml: dio: ^5.4.0
2import 'package:dio/dio.dart';
3
4// ── Basic Dio Setup ──
5class ApiClient {
6 late final Dio _dio;
7
8 ApiClient() {
9 _dio = Dio(BaseOptions(
10 baseUrl: 'https://api.example.com/v1',
11 connectTimeout: const Duration(seconds: 10),
12 receiveTimeout: const Duration(seconds: 10),
13 headers: {
14 'Content-Type': 'application/json',
15 'Accept': 'application/json',
16 },
17 ));
18
19 // Add interceptors
20 _dio.interceptors.addAll([
21 LogInterceptor(requestBody: true, responseBody: true),
22 AuthInterceptor(),
23 RetryInterceptor(),
24 ]);
25 }
26
27 // GET request
28 Future<List<Post>> getPosts() async {
29 final response = await _dio.get('/posts');
30 return (response.data as List)
31 .map((json) => Post.fromJson(json))
32 .toList();
33 }
34
35 // POST request
36 Future<Post> createPost(String title, String body) async {
37 final response = await _dio.post('/posts', data: {
38 'title': title,
39 'body': body,
40 });
41 return Post.fromJson(response.data);
42 }
43
44 // PUT request with path parameter
45 Future<Post> updatePost(int id, Map<String, dynamic> data) async {
46 final response = await _dio.put('/posts/$id', data: data);
47 return Post.fromJson(response.data);
48 }
49
50 // DELETE request
51 Future<void> deletePost(int id) async {
52 await _dio.delete('/posts/$id');
53 }
54
55 // File upload with progress
56 Future<String> uploadImage(File file) async {
57 final formData = FormData.fromMap({
58 'image': await MultipartFile.fromFile(
59 file.path,
60 filename: 'upload.jpg',
61 ),
62 });
63 final response = await _dio.post(
64 '/upload',
65 data: formData,
66 onSendProgress: (sent, total) {
67 print('Upload: ${(sent / total * 100).toStringAsFixed(0)}%');
68 },
69 );
70 return response.data['url'];
71 }
72}
dart
1// ── AUTH INTERCEPTOR (Token Refresh) ──
2class AuthInterceptor extends Interceptor {
3 @override
4 void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
5 final token = AuthService.instance.accessToken;
6 if (token != null) {
7 options.headers['Authorization'] = 'Bearer $token';
8 }
9 handler.next(options);
10 }
11
12 @override
13 void onError(DioException err, ErrorInterceptorHandler handler) async {
14 if (err.response?.statusCode == 401) {
15 // Token expired: try to refresh
16 try {
17 final newToken = await AuthService.instance.refreshToken();
18 err.requestOptions.headers['Authorization'] = 'Bearer $newToken';
19
20 // Retry the original request
21 final response = await Dio().fetch(err.requestOptions);
22 handler.resolve(response);
23 return;
24 } catch (_) {
25 AuthService.instance.logout();
26 }
27 }
28 handler.next(err);
29 }
30}
31
32// ── CENTRALIZED ERROR HANDLING ──
33class ApiException implements Exception {
34 final String message;
35 final int? statusCode;
36
37 ApiException(this.message, {this.statusCode});
38
39 factory ApiException.fromDioError(DioException error) {
40 switch (error.type) {
41 case DioExceptionType.connectionTimeout:
42 case DioExceptionType.receiveTimeout:
43 return ApiException('Connection timed out', statusCode: 408);
44 case DioExceptionType.badResponse:
45 final code = error.response?.statusCode;
46 final msg = error.response?.data?['message'] ?? 'Server error';
47 return ApiException(msg, statusCode: code);
48 case DioExceptionType.connectionError:
49 return ApiException('No internet connection');
50 default:
51 return ApiException('Something went wrong');
52 }
53 }
54}
55
56// Wrap calls with error handling:
57Future<Result<T>> safeApiCall<T>(Future<T> Function() call) async {
58 try {
59 final data = await call();
60 return Success(data);
61 } on DioException catch (e) {
62 return Failure(ApiException.fromDioError(e).message);
63 }
64}

Interceptor Execution Order

💡 Interceptor Execution Order

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.

API Client Reliability Model

Production API layers need consistency guarantees:

  • Standardize request timeout and retry policies by endpoint criticality.
  • Centralize error mapping from transport errors to domain-friendly failures.
  • Track request IDs for debugging across client and server logs.
  • Keep auth refresh logic idempotent to avoid retry storms.

Reliable API foundations reduce cascading failures in higher app layers.

Dio Production Checklist

  • Interceptors are ordered intentionally and documented.
  • 401 handling retries once and avoids infinite loops.
  • Network and parsing errors map to user-safe messages.
  • Large uploads and downloads expose progress and cancellation controls.
  • Critical endpoints have test coverage for success, timeout, and server error paths.

This Lesson In Simple Words

Build robust API layers with Dio, interceptors, and caching. Networking lessons teach your app how to request, store, and display remote data safely.

Your level focus

Operate with production and interview-level clarity.

One practical habit

Always model loading, success, empty, and error states before hooking the UI.

Deep Understanding Guide

Why this lesson matters

Most production bugs happen at data boundaries: slow networks, bad payloads, and error states.

Study flow for better retention

  1. Tie each concept to scale, failure handling, and delivery strategy.
  2. Treat every network call as unreliable and design graceful fallback behavior.
  3. If you can defend trade-offs under constraints, your understanding is strong.

Common Mistakes To Avoid

  • Triggering API calls inside build methods and causing duplicate requests.
  • Assuming response fields always exist without null checks or parsing safeguards.
  • Displaying backend errors directly to users without safe messaging.
  • Skipping retry and offline handling for key user actions.

Practice Sprint (15-25 Minutes)

  • Before running sample code, predict output and behavior in one sentence.
  • Implement one repository with timeout, retry, and typed parsing.
  • Add pull-to-refresh and compare stale vs fresh data behavior.
  • Create a clear UI state for empty list and network failure cases.
  • Complete the required exercises without using hints on the first attempt.
  • Answer this question out loud before checking quiz options: "What is the main advantage of Dio over the basic http package?".

Quick Glossary

  • build: The method that describes UI for the current state.

Code Comprehension Drill

  • State the purpose of the code block in one line before reading details.
  • Mark inputs, state changes, and final output.
  • Change one small value and predict what should happen before running.
  • Run again and compare your prediction with actual behavior.

Architecture Lens

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.

Lesson Completion Checklist

  • I can explain "REST APIs with Dio" in simple words without reading notes.
  • I can describe one real app situation where this concept is required.
  • I know at least one mistake to avoid: Triggering API calls inside build methods and causing duplicate requests.
  • I can modify one code sample and correctly predict the behavior change.
  • I can finish required exercises with understanding, not trial-and-error guesses.

Frequently Asked Questions

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.

What does an interceptor do when it receives a 401 response?

A 401 status means the token has expired. A well-designed auth interceptor attempts to refresh the token and retry the original request transparently.

How do you upload a file with Dio?

Dio uses FormData.fromMap with MultipartFile.fromFile to create multipart form uploads, similar to HTML form file uploads.

Suggest Improvement

Something seems incorrect, unclear, or missing? Let us know.

About The Author

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