Most Flutter apps we inherit have the same networking bug: three screens fire requests at once, the access token has expired, and all three try to refresh it. One succeeds, two fail with a revoked refresh token, and the user is logged out for no visible reason. This tutorial builds an HTTP layer that avoids that, using Dio.
Goals
- One place that attaches credentials.
- Exactly one token refresh at a time, however many requests fail together.
- Retries only where they are safe.
- Errors the UI can handle without parsing strings.
Set up a single client
Create one Dio instance behind your dependency injection of choice (Riverpod, get_it). Set baseUrl, sensible connectTimeout, receiveTimeout and sendTimeout, and never construct Dio ad hoc inside a screen.
final dio = Dio(BaseOptions(
baseUrl: 'https://api.example.com',
connectTimeout: const Duration(seconds: 10),
receiveTimeout: const Duration(seconds: 20),
));
Use a second, bare Dio instance for the refresh call itself. If the refresh request goes through the interceptor you are about to write, a 401 on refresh will recurse.
Attach the token
class AuthInterceptor extends QueuedInterceptor {
AuthInterceptor(this._tokens, this._refreshDio, this._retryDio);
final TokenStore _tokens;
final Dio _refreshDio; // no interceptors
final Dio _retryDio; // replays the original request
@override
void onRequest(RequestOptions options, RequestInterceptorHandler handler) async {
final token = await _tokens.accessToken();
if (token != null) options.headers['Authorization'] = 'Bearer $token';
handler.next(options);
}
}
Single-flight refresh
QueuedInterceptor serialises error handling, which helps, but do not rely on it alone. Keep an explicit in-flight future so concurrent failures share one refresh:
Future<String>? _refreshing;
Future<String> _refresh() => _refreshing ??= _doRefresh().whenComplete(() {
_refreshing = null;
});
Future<String> _doRefresh() async {
final refreshToken = await _tokens.refreshToken();
if (refreshToken == null) throw const SessionExpired();
final res = await _refreshDio.post('/auth/refresh',
data: {'refresh_token': refreshToken});
await _tokens.save(res.data['access_token'], res.data['refresh_token']);
return res.data['access_token'] as String;
}
@override
void onError(DioException err, ErrorInterceptorHandler handler) async {
final is401 = err.response?.statusCode == 401;
final alreadyRetried = err.requestOptions.extra['retried'] == true;
if (!is401 || alreadyRetried) return handler.next(err);
try {
final token = await _refresh();
final opts = err.requestOptions
..headers['Authorization'] = 'Bearer $token'
..extra['retried'] = true;
handler.resolve(await _retryDio.fetch(opts));
} on SessionExpired {
handler.reject(err);
}
}
The retried flag guarantees a request is replayed once at most. If the refresh itself fails with 401 or 400, clear tokens and emit a signed-out event on a stream your router listens to, instead of navigating from inside the interceptor.
If your backend rotates refresh tokens, persist the new pair before replaying anything, and make the write atomic.
Retry only what is safe
A retry is safe when the request is idempotent or carries an idempotency key. GET, HEAD, PUT and DELETE normally qualify. A POST that creates an order does not, unless the server accepts an Idempotency-Key header.
bool _retryable(DioException e) {
final method = e.requestOptions.method;
final idempotent = {'GET', 'HEAD', 'PUT', 'DELETE'}.contains(method) ||
e.requestOptions.headers.containsKey('Idempotency-Key');
final transient = e.type == DioExceptionType.connectionTimeout ||
e.type == DioExceptionType.connectionError ||
(e.response?.statusCode ?? 0) >= 502 && (e.response!.statusCode! <= 504);
return idempotent && transient;
}
Back off exponentially with jitter, cap attempts at three, and honour a Retry-After header on 429 and 503 responses. Do not retry 4xx errors other than 408 and 429; they will fail the same way again.
Typed errors
Map DioException into a sealed class at the repository boundary so widgets never import Dio:
sealed class ApiFailure { const ApiFailure(); }
class Offline extends ApiFailure { const Offline(); }
class Unauthorized extends ApiFailure { const Unauthorized(); }
class Validation extends ApiFailure {
const Validation(this.fields);
final Map<String, String> fields;
}
class ServerError extends ApiFailure { const ServerError(this.status); final int status; }
ApiFailure mapError(DioException e) => switch (e.type) {
DioExceptionType.connectionError ||
DioExceptionType.connectionTimeout => const Offline(),
_ => switch (e.response?.statusCode) {
401 => const Unauthorized(),
422 => Validation(_fields(e.response?.data)),
final int s => ServerError(s),
null => const Offline(),
},
};
The compiler then forces every screen to decide what each failure means.
Order your interceptors
Interceptor order matters: logging first (with Authorization redacted), then auth, then retry. If retry runs before auth, a 401 will be retried with the same stale token.
Test with a fake adapter
You do not need a network to test any of this. Implement HttpClientAdapter (or use http_mock_adapter) to script responses:
- Fire five parallel requests with an expired token; the adapter returns 401 for the old token. Assert the refresh endpoint was called exactly once and all five requests succeeded.
- Make the refresh endpoint return 401. Assert tokens are cleared and every request fails with
Unauthorized. - Return 503 twice then 200 on a GET; assert success after two retries. Repeat with a POST lacking an idempotency key and assert a single attempt.
Checklist
- One shared Dio instance; a separate bare one for refresh.
- Single in-flight refresh future.
- A per-request replay flag.
- Retries limited to idempotent, transient failures, with jittered backoff.
- Sealed error types at the repository boundary.
- Tokens in secure storage, never logged.
If you are untangling an inherited networking layer or planning a Flutter app that has to survive poor connectivity, our Flutter consultants do this kind of work regularly. Get in touch to talk it through.