Member-only story
Flutter — Using Interceptor in Dio for Flutter to Refresh Token
Step by Step guide using Interceptor with Dio in Flutter.
2 min readSep 15, 2021
Dio is a powerful Http client for Dart, which supports Interceptors, Global configuration, FormData, Request Cancellation, File downloading, Timeout etc.
Let’s dive right in to the solution 😊
this.api = Dio(); this.api.interceptors.add(InterceptorsWrapper(
onError: (error) async {
if (error.response?.statusCode == 403 ||
error.response?.statusCode == 401) {
await refreshToken();
return _retry(error.request);
}
return error.response;
}));
Basically what is going on is it checks to see if the error is a 401
or 403
, which are common auth errors, and if so, it will refresh the token and retry the response. My implementation of refreshToken()
looks like the following, but this may vary based on your api:
Future<void> refreshToken() async {
final refreshToken = await this._storage.read(key: 'refreshToken');
final response =
await this.api.post('/users/refresh', data: {'token': refreshToken}); if (response.statusCode == 200) {
this.accessToken = response.data['accessToken']…