I've created a package for the same [dio_refresh](https://pub.dev/packages/dio_refresh)
```dart
final dio = Dio();
// Define the TokenManager instance.
final tokenManager = TokenManager.instance;
tokenManager.setToken(
TokenStore(
accessToken: authToken,
refreshToken: refreshToken,
),
);
// Add the DioRefreshInterceptor.
dio.interceptors.add(DioRefreshInterceptor(
tokenManager: tokenManager,
authHeader: (tokenStore) {
if (tokenStore.accessToken == null) {
return {};
}
return {
'Authorization': 'Bearer ${tokenStore.accessToken}',
};
},
shouldRefresh: (response) =>
response?.statusCode == 401 || response?.statusCode == 403,
onRefresh: (dio, tokenStore) async {
final response = await dio.post('/refresh', data: {
'refresh_token': tokenStore.refreshToken,
});
return TokenStore(
accessToken: response.data['accessToken'],
refreshToken: response.data['refreshToken'],
);
},
));
```
This package will refresh the token whenever the token expires, and retries the failed APIs, and if any other API is being called while the refresh is going on, they'll wait until the refresh completes
I've created a package for the same [dio_refresh](https://pub.dev/packages/dio_refresh)
```dart
final dio = Dio();
// Define the TokenManager instance.
final tokenManager = TokenManager.instance;
tokenManager.setToken(
TokenStore(
accessToken: authToken,
refreshToken: refreshToken,
),
);
// Add the DioRefreshInterceptor.
dio.interceptors.add(DioRefreshInterceptor(
tokenManager: tokenManager,
authHeader: (tokenStore) {
if (tokenStore.accessToken == null) {
return {};
}
return {
'Authorization': 'Bearer ${tokenStore.accessToken}',
};
},
shouldRefresh: (response) =>
response?.statusCode == 401 || response?.statusCode == 403,
onRefresh: (dio, tokenStore) async {
final response = await dio.post('/refresh', data: {
'refresh_token': tokenStore.refreshToken,
});
return TokenStore(
accessToken: response.data['accessToken'],
refreshToken: response.data['refreshToken'],
);
},
));
```
This package will refresh the token whenever the token expires, and retries the failed APIs, and if any other API is being called while the refresh is going on, they'll wait until the refresh completes