Dio with interceptors in Flutter: solved exercise
Dio with interceptors in Flutter: solved exercise
The http package covers simple cases, but production apps need interceptors: logic that runs automatically on every request or response without repeating code. Dio implements them with a clean API and is the most widely used HTTP client in Flutter for production.
Problem statement
Configure a Dio client that:
- Automatically adds the
Authorization: Bearer <token>header to all requests. - Logs method, URL, and response code to the console.
- Catches 401 errors (expired session) centrally and converts them to a typed exception.
Build a screen that uses this client to load a post and shows loading, result, and error states.
Dependencies
Flutter solution
Expected result
- Tapping the button shows the loader and logs
→ GET https://jsonplaceholder.typicode.com/posts/1to console. - After the response:
← 200 https://...and the post title on screen. - The
Authorization: Bearer my-test-tokenheader is added automatically to all requests.
Common mistakes
- Adding interceptors after the first request: interceptors are evaluated in the order they are added; add them when building the client, not in
initState. - Not calling
handler.next(): if you forget to callnextinonRequest, the request hangs indefinitely. - Catching generic
Exceptioninstead ofDioException:DioExceptioncontainsresponse,requestOptions, andtype; use those fields for precise diagnostics.
When to use Dio vs http
| Need | http | Dio |
|---|---|---|
| Simple GET without auth | ✅ | ✅ |
| Global interceptors | ❌ | ✅ |
| Request cancellation | ❌ | ✅ |
| File upload (multipart) | verbose | ✅ |
| Automatic retry | manual | ✅ (via plugin) |
Practical use
In any app with an authenticated backend, this pattern eliminates copy-pasting the auth header on every request and centralizes expired session handling, which otherwise gets scattered throughout the app.
Recommended next exercise
- Flutter timeout and retry: solved exercise
- Auth with refresh token in Flutter: solved exercise
- Loading, error and empty states in Flutter: solved exercise
- All Flutter exercises
Guided practice and next step
- More Flutter exercises
- C exercises to strengthen fundamentals
- Programming in C in 100 Solved Exercises
- View the book on Amazon (included in Kindle Unlimited)
- Subscribe to the newsletter
FAQ
Can I have multiple active interceptors at once?
Yes. Dio executes them as a chain in the order they were registered. Response and error interceptors run in reverse order.
How do I cancel an in-flight request?
Pass a CancelToken to the request and call cancelToken.cancel() when needed (e.g., when the widget is unmounted).
Is Dio compatible with null safety?
Yes. Since version 5.x it is null-safe and supports generics: _dio.get<Map<String, dynamic>>(...) for strong typing.