遇到HTTP 401时颤振重定向 [英] Flutter redirect when encountered http 401

查看:42
本文介绍了遇到HTTP 401时颤振重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在有这样的导航:

main>应用>帐户>地址

现在我遇到问题,如果用户获取地址并且他们的会话过期,如何将他们重定向回登录页面?仍然扑朔迷离,找不到解决方案如何将未经身份验证的状态发送到 main ,以便它可以重定向它.

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.

我正在使用dio和MobX软件包.

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;
    }));

我试图将Observer放在我的 main.dart 上,以继续检查状态

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
});

有解决方案吗?

我唯一能想到的解决方案是检查每次调用API(每次存储).如果401会自动将其发送回登录页面.但是这种方法将非常多余.

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.

推荐答案

我遇到了同样的问题.要解决此问题,我们需要一个没有上下文 Navigation (导航),才能在拦截器上导航.在MaterialApp之前初始化Api服务.允许MaterialApp传递顶部导航器的navigatorKey.

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.

我在定义apiservice的拦截器时创建 GlobalKey ,并将其用于返回MaterialApp.

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

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

并创建apiService

and create apiService

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

创建材质应用时:

MaterialApp(
    ...
    navigatorKey: navigator,
    ...
)

这篇关于遇到HTTP 401时颤振重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆