编写对应的登录校验拦截器,对每次的请求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.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;
}
}
}
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,
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