原因:Flutter在一些包的层级比较多子Widget里无法直接用过Navigator.of(context).push方法来进行跳转,主要是因为子Widget的Context无法执行跳转操作,只能使用页面的BuildContext来进行跳转,解决办法有两个
1.在需要点击跳转的子View外部包一层Builder如下
child: Builder(builder: (context) {
return GestureDetector(
onTap: () {
NavigationUtil.startWidget(context, widget);//自己封装的跳转方法,忽略
},
child: Text(CommonStringConfig.Save),
);
}
2.第一种方法比较繁琐,必须是直接作用于跳转子Widget的父Widget,我尝试使用在基类中包括Buidler,结果也是没用的,第二种方法是利用GlobalKey来完成跳转,使用非常简单,但是也有很大的缺点,先看用法
final navigatorKey = GlobalKey<NavigatorState>();
Widget build(BuildContext context) => MaterialApp {
navigatorKey: navigatorKey
onGenerateRoute : .....
};
在new MaterialApp的时候给MaterialApp加上navigatorKey属性,然后利用
navigatorKey.currentState.push(....);
方法来跳转,这种用法的好处是不受任何View约束,不需要传递context
But!!!!
请看官方的解释
Using GlobalKey is relatively expensive and should be avoided if at all possible - while you can use it, that doesn't mean you should unless you have a specific use-case that necessitates it. And I'd argue that if you do need to pass it around, you can probably refactor your code to avoid it. You definitely shouldn't be passing it around! The whole mechanism of Nativator.of(context) is meant to avoid having to pass things around.
官方表示引用GlobalKey是一种“昂贵”的选择,也就是开销会非常大,所以经过一天的实验,我还是选择了第一种用法,如果是你,你会怎样选择?