Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter redirect when encountered http 401

Tags:

flutter

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.

like image 495
ssuhat Avatar asked Nov 19 '25 15:11

ssuhat


1 Answers

I have the same issue. To resolve this issue, we need a Navigation without context to can navigate on interceptors. Api service is initializated before MaterialApp. MaterialApp is allowed pass the navigatorKey for top navigator.

I create GlobalKey when define interceptors of apiservice and use it for return MaterialApp.

  final GlobalKey<NavigatorState> navigator;//Create a key for navigator

and create apiService

void _configAuthApiService() {
    ...
    if (error.response?.statusCode == 401) {
        navigator.currentState.pushReplacementNamed('/login');
    }
    ...
}

When create material app:

MaterialApp(
    ...
    navigatorKey: navigator,
    ...
)
like image 65
dangngocduc Avatar answered Nov 21 '25 07:11

dangngocduc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!