Flutter無法跳轉(zhuǎn)頁面的解決方法(push方法無效)

原因: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)過一天的實驗,我還是選擇了第一種用法,如果是你,你會怎樣選擇?

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容