refreshTokenTemplate top-level property
This is code to be generated.
Implementation
String refreshTokenTemplate = """
/*
* Created by DartGenX CLI tool on ${DateFormat('EEE, dd MMM yyyy, h:mm a').format(DateTime.now())}
*/
import 'dart:async';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
class RefreshToken {
static final RefreshToken _instance = RefreshToken._();
static RefreshToken get instance => _instance;
RefreshToken._();
Completer<dynamic>? _completer;
bool isAccessTokenFetch = false;
SharedPreferences? prefs;
Dio dio = Dio(
BaseOptions(
baseUrl: "<YOUR-BASE-URL>",
),
);
int retryCount = 0;
final int maxRetries = 3; // You can change the maximum number of retries from here.
void callRefreshToken({required DioException err, required ErrorInterceptorHandler handler}) async {
// If already tried refreshing, stop further recursion
if (retryCount > maxRetries) {
debugPrint('❌ Max retries reached for token refresh.');
handler.reject(err);
return;
}
if (_completer != null) {
if (_completer!.isCompleted && isAccessTokenFetch) {
handler.resolve(await dio.fetch(err.requestOptions));
} else {
await _completer!.future.then((value) async {
isAccessTokenFetch = true;
// Get the shared preferences instance.
prefs ??= await SharedPreferences.getInstance();
// Save new tokens to shared preferences
await prefs!.setString('accessToken', "<YOUR-NEW-ACCESS-TOKEN>");
await prefs!.setString('refreshToken', "<YOUR-NEW-REFRESH-TOKEN>");
// Update the access token to the header
err.requestOptions.headers['Authorization'] = 'Bearer <YOUR-NEW-ACCESS-TOKEN>';
// This will called the api again which has thrown the unauthorized error.
handler.resolve(await dio.fetch(err.requestOptions));
retryCount = 0;
}, onError: (err) {
retryCount++;
callRefreshToken(err: err, handler: handler);
});
}
} else {
_completer = Completer();
prefs ??= await SharedPreferences.getInstance();
await dio.post("<API-ENDPOINT-FOR-GETTING-NEW-ACCESS-TOKEN-USING-REFRESH-TOKEN>", data: {"token": prefs!.getString('refreshToken') ?? ''}).then((value) {
_completer!.complete(value);
}, onError: (err) {
_completer!.completeError(err);
});
_completer = null;
}
}
}
""";