1. 程式人生 > 實用技巧 >宇智波程式筆記34-【Flutter 實戰】路由堆疊詳解

宇智波程式筆記34-【Flutter 實戰】路由堆疊詳解

老孟導讀:Flutter中路由是非常重要的部分,任何一個應用程式都離不開路由管理,此文講解路由相關方法的使用和路由堆疊的變化。

Flutter 路由管理中有兩個非常重要的概念:

  • Route:路由是應用程式頁面的抽象,對應 Android 中 Activity 和 iOS 中的 ViewController,由 Navigator 管理。
  • Navigator:Navigator 是一個元件,管理和維護一個基於堆疊的歷史記錄,通過 push 和 pop 進行頁面的跳轉。

push 和 pop

假設現在有2個頁面 A 和 B,A中有一個按鈕,點選跳轉到 B 頁面,A 頁面程式碼:

classAPageextendsStatelessWidget{
@override
Widgetbuild(BuildContextcontext){
returnContainer(
alignment:Alignment.center,
child:RaisedButton(
child:Text('A頁面'),
onPressed:(){
Navigator.of(context).push(MaterialPageRoute(builder:(context){
returnBPage();
}));
},
),
);
}
}

B 頁面程式碼:

classBPageextendsStatelessWidget{
@override
Widgetbuild(BuildContextcontext){
returnScaffold(
body:Container(
alignment:Alignment.center,
child:RaisedButton(
child:Text('B頁面'),
onPressed:(){

},
),
),
);
}
}

當應用程式位於A頁面時,路由堆疊中只有A,點選按鈕跳轉到B頁面,路由堆疊中有 B 和 A,且 B 處於棧頂。

點選 B 頁面的按鈕返回到 A 頁面,修改 B 頁面按鈕點選事件:

RaisedButton(
child:Text('B頁面'),
onPressed:(){
Navigator.of(context).pop();
},
)

路由堆疊的變化:

上面案例的效果是從 B 頁面跳轉到 A 頁面,那是否也可以使用 push 方法?修改 B 頁面按鈕點選事件:

RaisedButton(
child:Text('B頁面'),
onPressed:(){
Navigator.of(context).push(MaterialPageRoute(builder:(context){
returnAPage();
}));
},
)

從效果上看也可以跳轉到 A 頁面,路由堆疊:

那是否可以使用 push 代替 pop 呢?答案肯定是不可以的,

  1. 試想如下場景,進入購物App,展示購物列表,點選其中一個進入商品詳細頁面,使用 push 再次進入購物列表,然後在進入商品詳細頁面...,如此反覆,路由堆疊中將會存放大量的購物列表和商品詳細頁面的路由,點選返回按鈕,會將反覆顯示購物列表和商品詳細頁面。
  2. 頁面切換時路由動畫 push 和 pop 是不同。

maybePop 和 canPop

上面案例如果點選 A 頁面按鈕直接呼叫 pop 會如何?

RaisedButton(
child:Text('A頁面'),
onPressed:(){
Navigator.of(context).pop();
},
)

在 A 頁面時路由堆疊中只有 A,呼叫 pop 後,路由堆疊變化:

此時路由堆疊為空,沒有可顯示的頁面,應用程式將會退出或者黑屏,好的使用者體驗不應如此,此時可以使用 maybePop,maybePop 只在路由堆疊有可彈出路由時才會彈出路由。

上面的案例在 A 頁面執行maybePop:

RaisedButton(
child:Text('A頁面'),
onPressed:(){
Navigator.of(context).maybePop();
},
)

點選後不會出現彈出路由,因為當前路由堆疊中只有 A,在 B頁面執行maybePop,將會返回到 A 頁面。

也可以通過 canPop 判斷當前是否可以 pop:

RaisedButton(
child:Text('B頁面'),
onPressed:(){
if(Navigator.of(context).canPop()){
Navigator.of(context).pop();
}
},
)

pushNamed

pushNamed 是命名路由的方式,需要在 MaterialApp 中配置路由名稱:

MaterialApp(
title:'FlutterDemo',
routes:<String,WidgetBuilder>{
'/A':(context)=>APage(),
'/B':(context)=>BPage(),
},
home:Scaffold(
body:APage(),
),
)

從 A 跳轉到 B:

RaisedButton(
child:Text('A頁面'),
onPressed:(){
Navigator.of(context).pushNamed('/B');
},
)

pushReplacementNamed 和 popAndPushNamed

有A、B、C 三個頁面,A頁面通過 pushNamed 跳轉到 B:

RaisedButton(
child:Text('A頁面'),
onPressed:(){
Navigator.of(context).pushNamed('/B');
},
)

B 通過 pushReplacementNamed 跳轉到 C:

RaisedButton(
child:Text('B頁面'),
onPressed:(){
Navigator.of(context).pushReplacementNamed('/C');
},
)

點選 C 頁面按鈕執行 pop:

RaisedButton(
child:Text('C頁面'),
onPressed:(){
if(Navigator.of(context).canPop()){
Navigator.of(context).pop();
}
},
)

點選 C 頁面按鈕直接返回到了 A 頁面,而不是 B 頁面,因為 B 頁面使用 pushReplacementNamed 跳轉,路由堆疊變化:

B 頁面跳轉到 C 頁面,使用 popAndPushNamed:

RaisedButton(
child:Text('B頁面'),
onPressed:(){
Navigator.of(context).popAndPushNamed('/C');
},
)

popAndPushNamed 路由堆疊和 pushReplacementNamed 是一樣,唯一的區別就是 popAndPushNamed 有 B 頁面退出動畫。

popAndPushNamed 和 pushReplacementNamed 使當前頁面不在路由堆疊中,所以通過 pop 無法返回此頁面。

適用場景:

  • 歡迎頁面:應用程式開啟後首先進入歡迎介面,然後進入首頁,進入首頁後不應該再進入歡迎介面。
  • 登入頁面:登入成功後進入相關頁面,此時按返回按鈕,不應再進入登入頁面。

pushNamedAndRemoveUntil

有如下場景,應用程式進入首頁,點選登入進入登入頁面,然後進入註冊頁面或者忘記密碼頁面...,登入成功後進入其他頁面,此時不希望返回到登入相關頁面,此場景可以使用 pushNamedAndRemoveUntil。

有A、B、C、D 四個頁面,A 通過push進入 B 頁面,B 通過push進入 C 頁面,C 通過pushNamedAndRemoveUntil進入 D 頁面同時刪除路由堆疊中直到 /B 的路由,C 頁面程式碼:

RaisedButton(
child:Text('C頁面'),
onPressed:(){
Navigator.of(context).pushNamedAndRemoveUntil('/D',ModalRoute.withName('/B'));
},
),

D 頁面按鈕執行 pop:

RaisedButton(
child:Text('D頁面'),
onPressed:(){
Navigator.of(context).pop();
},
)

從 C 頁面跳轉到 D 頁面路由堆疊變化:

Navigator.of(context).pushNamedAndRemoveUntil('/D',ModalRoute.withName('/B'));

表示跳轉到 D 頁面,同時刪除D 到 B 直接所有的路由,如果刪除所有路由,只儲存 D:

Navigator.of(context).pushNamedAndRemoveUntil('/D',(Routeroute)=>false);

路由堆疊變化:

popUntil

有如下場景,在入職新公司的時候,需要填寫各種資訊,這些資訊分為不同部分,比如基本資訊、工作資訊、家庭資訊等,這些不同模組在不同頁面,填寫資訊時可以返回上一頁,也可以取消,取消返回到首頁,此場景可以使用 popUntil,一直 pop 到指定的頁面。

有A、B、C、D 四個頁面,D 頁面通過 popUntil 一直返回到 A 頁面,D 頁面程式碼:

RaisedButton(
child:Text('D頁面'),
onPressed:(){
Navigator.of(context).popUntil(ModalRoute.withName('/A'));
},
)

路由堆疊變化:

傳遞資料

有如下場景,商品列表頁面,點選跳轉到商品詳情頁面,商品詳情頁面需要商品的唯一id或者商品詳情資料,有兩種方式傳遞資料:

第一種:通過建構函式方式:

classProductDetailextendsStatelessWidget{
finalProductInfoproductInfo;

constProductDetail({Keykey,this.productInfo}):super(key:key);

@override
Widgetbuild(BuildContextcontext){
returnContainer();
}
}

跳轉程式碼:

Navigator.of(context).push(MaterialPageRoute(builder:(context){
returnProductDetail(productInfo:productInfo,);
}));

此種方式無法用於命名路由的跳轉方式。

第二種:通過命名路由設定引數的方式:

A 頁面傳遞資料,

RaisedButton(
child:Text('A頁面'),
onPressed:(){
Navigator.of(context).pushNamed('/B',arguments:'來自A');
},
)

B 頁面通過ModalRoute.of(context).settings.arguments接收資料:

RaisedButton(
child:Text('${ModalRoute.of(context).settings.arguments}'),
onPressed:(){
Navigator.of(context).pushNamed('/C');
},
)

返回資料

B 頁面返回程式碼:

RaisedButton(
child:Text('${ModalRoute.of(context).settings.arguments}'),
onPressed:(){
Navigator.of(context).pop('從B返回');
},
)

A 頁面接收返回的資料:

classAPageextendsStatefulWidget{
@override
_APageStatecreateState()=>_APageState();
}

class_APageStateextendsState<APage>{
String_string='A頁面';

@override
Widgetbuild(BuildContextcontext){
returnScaffold(
body:Container(
alignment:Alignment.center,
child:RaisedButton(
child:Text(_string),
onPressed:()async{
varresult=
awaitNavigator.of(context).pushNamed('/B',arguments:'來自A');
setState((){
_string=result;
});
},
),
),
);
}
}

push 相關方法返回 Future 型別,使用 await 等待返回結果。

你可能還喜歡

    •  <artifactId>spring-boot-starter-freemarker</artifactId>
        
        * 1. The www.yachengyl.cn protocol www.fudayulpt.cn configured www.ued3zc.cn the client is inconsistent with the protocol of the server.
        
        * eg: consumer www.baichuangyule.cn www. jinmazx.cn www.bhylzc.cn protocol www.jintianxuesha.com= dubbo, provider only has other protocol services(rest).
        
        * 2. The registration www.xinhuihpw.com center www.wanyayuue.cn not robust and pushes illegal specification data.
        
        if (CollectionUtils.www.feihongyul.cn isEmptyMap(newUrlInvokerMap)) www.qiaoheibpt.com{
        
        logger.error(new www.shengrenpt.com IllegalStateException("urls to invokers error .invokerUrls.size :" + invokerUrls.size() + ", invoker.size www.baishenjzc.cn :0.
        
        List<Invoker<www.huanhua2zhuc.cn>> newInvokers = Collections.unmodifiableList(new ArrayList<>(newUrlInvokerMap.values(www.baihuayl7.cn)));
        
        // pre-route and build cache, notice www.shengrenyp.cn that route cache should build on www.shengrenyp.cn original Invoker list.
        
        // toMergeMethodInvokerMap(www.xinchenptgw.cn ) will wrap some invokers www.xinhuihpw.com having www.youxiu2pt.cn different groups, those wrapped invokers not should be routed.
        
        routerChain.setInvokers(www.haojuptzc.cn newInvokers);
        
        this.invokers =www.wujiu5zhuce.cn