I have a navigation like this for now:
main > app > account > address
right now i encountered issue if user fetching address and their session expires how can I redirect them back to login page? Still new to flutter, can't find the esolution how to send unauthenticated status to main so it can redirect it.
I'm using dio and MobX package.
dio.interceptors
.add(InterceptorsWrapper(onRequest: (RequestOptions options) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
String token = prefs.getString('access_token');
if (token != null) {
options.headers['Authorization'] = 'Bearer $token';
}
options.headers['Accept'] = 'application/json';
return options; //continue
}, onResponse: (Response response) {
final int statusCode = response.statusCode;
var results = {};
if (statusCode == 200 || statusCode == 201 || statusCode == 204) {
final dynamic decodeResponse = this.decodeResponse(response);
bool responseIsList = decodeResponse is List;
if (!responseIsList && decodeResponse['token'] != null) {
final token = decodeResponse['token'];
setAuthorizationToken(token['access_token'], token['refresh_token']);
}
if (responseIsList) {
return decodeResponse;
} else {
final resultToAdd = decodeResponse;
results.addAll(resultToAdd);
return results;
}
}
return response;
}, onError: (DioError e) async {
final r = e.response;
if (r.statusCode == 401) {
AuthStore().unauthorize(prefs: _sharedPreferences);
}
if (r != null) {
return {"has_error": true, ...r.data};
}
// Do something with response error
return e;
}));
I've tried to put Observer on my main.dart to keep checking on the status
@override
Widget build(BuildContext context) {
return Observer(builder: (_) {
if (store.statusAuth == 401) {
Navigator.pushReplacementNamed(context, '/'); // this is error
}
// other material app function
});
Any solution?
The solution only I can think of for now is checking every time API is called (every store). if 401 will automatically send it back to login page. but this approach will be very redundant.