原因:Flutter在一些包的層級比較多子Widget里無法直接用過Navigator.of(context).push方法來進行跳轉(zhuǎn),主要是因為子Widget的Context無法執(zhí)行跳轉(zhuǎn)操作,只能使用頁面的BuildContext來進行跳轉(zhuǎn),解決辦法有兩個
1.在需要點擊跳轉(zhuǎn)的子View外部包一層Builder如下
child: Builder(builder: (context) {
return GestureDetector(
onTap: () {
NavigationUtil.startWidget(context, widget);//自己封裝的跳轉(zhuǎn)方法,忽略
},
child: Text(CommonStringConfig.Save),
);
}
2.第一種方法比較繁瑣,必須是直接作用于跳轉(zhuǎn)子Widget的父Widget,我嘗試使用在基類中包括Buidler,結(jié)果也是沒用的,第二種方法是利用GlobalKey來完成跳轉(zhuǎn),使用非常簡單,但是也有很大的缺點,先看用法
final navigatorKey = GlobalKey<NavigatorState>();
Widget build(BuildContext context) => MaterialApp {
navigatorKey: navigatorKey
onGenerateRoute : .....
};
在new MaterialApp的時候給MaterialApp加上navigatorKey屬性,然后利用
navigatorKey.currentState.push(....);
方法來跳轉(zhuǎn),這種用法的好處是不受任何View約束,不需要傳遞context
But!?。。?br>
請看官方的解釋
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是一種“昂貴”的選擇,也就是開銷會非常大,所以經(jīng)過一天的實驗,我還是選擇了第一種用法,如果是你,你會怎樣選擇?