Flutter Dio 拦截器退出登录

文章目录

  • Flutter Dio 拦截器退出登录
    • 拦截器拦截登录失效事件
      • 编写登录校验拦截器
      • 对dio设置拦截器
      • 拦截器设置通用参数
    • 无context push登录页面
      • 设置通用的NavigatorState
      • 实现无context push页面
      • 为什么可以推

Flutter Dio 拦截器退出登录

拦截器拦截登录失效事件

编写登录校验拦截器

编写对应的登录校验拦截器,对每次的请求callback事件进行拦截,获取对应的resultCode(对应key名由公司业务决定),当捕获到token失效事件,进行特定处理。


/// Token拦截器
class LoginInterceptors extends InterceptorsWrapper {
  int _resultCode;
  String _resultMsg;

  LoginInterceptors();

  @override
  onRequest(RequestOptions options) async {
    return options;
  }

  @override
  onResponse(Response response) async {
    try {
      var responseJson = response.data;
      CommResult commResult = CommResult.fromJson(jsonDecode(responseJson));
      _resultCode = commResult.resultCode;
      _resultMsg = commResult.resultMsg;
      if (ResultCodeCon.login_err_code.contains(_resultCode)) {
        ToastUtils.show('登录失效了,请重新登录');
        UserManager.cleanUserInfo();
        HttpManage.getInstance().cancelAllRequest();
        NavigatorState navigatorState = MyApp?.navigatorKey?.currentState;
        if (navigatorState != null) {
          navigatorState.pushAndRemoveUntil(
              MaterialPageRoute(builder: (context) => LoginPage()),
              (route) => route == null);
        }
      } else {
        if (_resultCode != ResultCodeCon.success_code) {
          ToastUtils.show(_resultMsg);
        }
      }
    } catch (e) {
      print(e);
    }
    return response;
  }
}

对dio设置拦截器

    dio.interceptors.add(TokenInterceptors());

拦截器设置通用参数


/// Token拦截器
class TokenInterceptors extends InterceptorsWrapper {
  /// 用户信息
  LoginModel _loginModel;

  /// 版本信息
  PackageInfo _packageInfo;

  @override
  onRequest(RequestOptions options) async {
    //授权码
    if (_loginModel == null) {
      var authorizationCode = await getAuthorization();
      if (authorizationCode != null) {
        _loginModel = authorizationCode;
      }
    }
    if(_packageInfo==null){
      var packInfo=await getAppPackInfo();
      if(packInfo!=null){
        _packageInfo=packInfo;
      }
    }
    options.headers["X-AUTH-TOKEN"] = _loginModel?.resultData?.xAUTHTOKEN;
    options.headers["APP-VERSION"]=_packageInfo?.version;
    if (options.method == "post" || options.method == "POST") {
      options.data["groupId"] = 2;
      options.data["userId"] = _loginModel?.resultData?.userId;
      options.data["organizationId"] = _loginModel?.resultData?.organizationId;
      options.data["timeStamp"] = new DateTime.now().millisecond;
      options.data['data'] = json.encode(options.data);
    } else if (options.method == "get" || options.method == "GET") {
      options.queryParameters["groupId"] = 2;
      options.queryParameters["userId"] = _loginModel?.resultData?.userId;
      options.queryParameters["organizationId"] =
          _loginModel?.resultData?.organizationId;
      options.queryParameters["timeStamp"] = new DateTime.now().millisecond;
      options.queryParameters['data'] = json.encode(options.queryParameters);
    }
    return options;
  }

  @override
  onResponse(Response response) async {
    return response;
  }

  ///清除授权
  clearAuthorization() {
    this._loginModel = null;
    Sputils.remove(Config.TOKEN_KEY);
  }

  ///获取授权token
  getAuthorization() async {
    LoginModel loginModel = await UserManager.getLoginModel();
    if (loginModel == null) {
      print('找不到数据');
    } else {
      this._loginModel = loginModel;
      return loginModel;
    }
  }

  /// 获取版本信息
  getAppPackInfo() async {
    PackageInfo packageInfo = await PageInfoUtils.instance.getVersionInfo();
    if (packageInfo == null) {
      print('拿不到版本信息');
    } else {
      this._packageInfo = packageInfo;
      return packageInfo;
    }
  }
}

无context push登录页面

设置通用的NavigatorState

 static final GlobalKey navigatorKey =
      new GlobalKey();
return MaterialApp(
      navigatorKey: navigatorKey,
      debugShowCheckedModeBanner: false,
      title: Strings.STRING_APP,
      routes: {
        "/loginPage": (context) => LoginPage(),
      },
      theme: ThemeData(
        primaryColor: Colors.white,
        primaryColorBrightness: Brightness.light,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: ifLogin ? TabNavigator() : LoginPage(),
    );
  }

注意其中的

navigatorKey: navigatorKey,

实现无context push页面

  NavigatorState navigatorState = MyApp?.navigatorKey?.currentState;
        if (navigatorState != null) {
          navigatorState.pushAndRemoveUntil(
              MaterialPageRoute(builder: (context) => LoginPage()),
              (route) => route == null);
        }

为什么可以推

  @optionalTypeArgs
  static Future push(BuildContext context, Route route) {
    return Navigator.of(context).push(route);
  }
  static NavigatorState of(
    BuildContext context, {
    bool rootNavigator = false,
    bool nullOk = false,
  }) {
    final NavigatorState navigator = rootNavigator
        ? context.findRootAncestorStateOfType()
        : context.findAncestorStateOfType();
    assert(() {
      if (navigator == null && !nullOk) {
        throw FlutterError(
          'Navigator operation requested with a context that does not include a Navigator.\n'
          'The context used to push or pop routes from the Navigator must be that of a '
          'widget that is a descendant of a Navigator widget.'
        );
      }
      return true;
    }());
    return navigator;
  }

这里Navigator.of(context)获取的也是一个NavigatorState

你可能感兴趣的:(Flutter)