Dio: 在dio 的拦截器中怎么做路由跳转

Created on 24 Dec 2018  ·  5Comments  ·  Source: flutterchina/dio

拦截器中,登录信息失效,就跳登录页,可是我在dio这边拿不到context,有没有什么好的方案.

Most helpful comment

找到不需要context的方法了,看这里:https://stackoverflow.com/questions/52962112/how-to-navigate-without-context-in-flutter-app

You can set a global key for your navigation:

final GlobalKey navigatorKey = new GlobalKey();
Pass it to MaterialApp:

new MaterialApp(
title: 'MyApp',
onGenerateRoute: generateRoute,
navigatorKey: key,
);
Push routes:

navigatorKey.currentState.pushNamed('/someRoute');

All 5 comments

  1. 可以在路由跳转时将context保存为全局变量,需要注意,context可能会发生变化,但是在用于路由跳转的场景,目前笔者发现都是可以用的。
  2. 也可以将context通过options.extra参数传递到拦截器中,但这样一来,每个请求都要传一下context.

好的,谢谢,目前已经采用每个请求都把context传入的办法,除了多写点代码,目前还是没有问题.

网络不通情况下interceptor.response.onError里e.response为空拿不到options.extra怎么办

找到不需要context的方法了,看这里:https://stackoverflow.com/questions/52962112/how-to-navigate-without-context-in-flutter-app

You can set a global key for your navigation:

final GlobalKey navigatorKey = new GlobalKey();
Pass it to MaterialApp:

new MaterialApp(
title: 'MyApp',
onGenerateRoute: generateRoute,
navigatorKey: key,
);
Push routes:

navigatorKey.currentState.pushNamed('/someRoute');

解决了吗? 求分享代码

Was this page helpful?
0 / 5 - 0 ratings