I am trying to call an api with the help of provider if response is 401..but provider takes a context to call a function.. in my case is there any way to call a function with out context? following is my interceptor where I want to call function
class ExpiredTokenRetryPolicy extends RetryPolicy {
@override
Future<bool> shouldAttemptRetryOnResponse(BaseResponse response) async {
if (response.statusCode == 401) {
//perform token refresh,get the new token and update it in the secure storage
Provider.of<Auth>(context, listen: false).restoreAccessToken();
}
return false;
}
}
I am using provider to save response in variables therefore I cant use function directly following is my function
Future<void> restoreAccessToken() async {
final url = '${Ninecabsapi().urlHost}${Ninecabsapi().login}/$sessionId';
var response = await http.patch(
Uri.parse(url),
headers: {
'Content-Type': 'application/json; charset=UTF-8',
'Authorization': token!
},
body: json.encode(
{"refresh_token": refreshtoken},
),
);
var userDetails = json.decode(response.body);
if (response.statusCode == 401) {
print(userDetails['messages']);
}
print(userDetails);
sessionId = userDetails['data']['session_id'];
accessToken = userDetails['data']['access_token'];
accessTokenExpiryDate = DateTime.now().add(
Duration(seconds: userDetails['data']['access_token_expiry']),
);
refreshToken = userDetails['data']['refresh_token'];
refreshTokenExpiryDate = DateTime.now().add(
Duration(seconds: userDetails['data']['refresh_token_expiry']),
);
print(userDetails);
notifyListeners();
final prefs = await SharedPreferences.getInstance();
final userData = json.encode({
'sessionId': sessionId,
'refreshToken': refreshToken,
'refreshExpiry': refreshTokenExpiryDate!.toIso8601String(),
'accessToken': accessToken,
'accessTokenExpiry': accessTokenExpiryDate!.toIso8601String()
});
prefs.setString('userData', userData);
reset();
}
CodePudding user response:
No, the provider takes the context
because it use that to find the correct (closest) instance of your Auth
class.