Flutter › Networking with HTTP & Dio

How do Dio interceptors let you centrally add a shared authentication header to every single outgoing request, or centrally handle a genuine expired token error consistently across your entire app?

Intermediate

Answer

A Dio interceptor lets you properly hook into the request, response, or error lifecycle of essentially every single network call your app makes, and a genuinely common pattern uses an onRequest interceptor to automatically attach a shared authentication token header to every single outgoing request without needing to manually add it individually within every single separate API call, while a corresponding onError interceptor can properly detect a genuine expired authentication token, then automatically attempt to properly refresh that token and correctly retry the original genuinely failed request, all handled consistently in one single centralized location.
dio.interceptors.add(InterceptorsWrapper(
  onRequest: (options, handler) {
    options.headers['Authorization'] = 'Bearer $token';
    handler.next(options);
  },
));
Real-world example A social media app uses a single shared Dio interceptor to automatically attach the current user's own authentication token to every single one of the hundreds of separate API calls made throughout their entire app, avoiding the need to manually and repeatedly add that same header individually within each individual separate network call.

Common follow-ups: How do you actually properly implement automatic token refresh logic specifically within an onError interceptor?;Can a single Dio instance genuinely have several genuinely separate interceptors registered together at the exact same time?