之前使用普通路由實(shí)現(xiàn)了頁(yè)面跳轉(zhuǎn)扣汪,和可以帶參數(shù)跳轉(zhuǎn),今天使用另一種路由方式:命名路由锨匆,將頁(yè)面與路徑做映射崭别,起到命名作用。
命名路由主要是修改如下幾個(gè)地方:
(1)主頁(yè)面代碼如下:
final routes = {
"/search": (context) => SearchPage(),
"/settings": (context,{arguments}) => SettingsPage(
arguments: arguments
),
};
在materialApp里使用(固定寫(xiě)法):
onGenerateRoute: (RouteSettings settings) {
final String name = settings.name;
print(name);
final Function pageContentBuilder = this.routes[name];
if (pageContentBuilder != null) {
if (settings.arguments != null) {
final Route route = MaterialPageRoute(
builder: (context) =>
pageContentBuilder(context, arguments: settings.arguments));
return route;
} else {
final Route route = MaterialPageRoute(
builder: (context) => pageContentBuilder(context));
return route;
}
}
},
(2)觸發(fā)跳轉(zhuǎn)頁(yè)面代碼如下:
Navigator.pushNamed(context, "/settings",arguments:{"id":"123"});
(3)到達(dá)頁(yè)面的參數(shù)接受恐锣,代碼如下:
final arguments;
// args表示可能傳入的參數(shù)列表
SettingsPage({this.arguments});
@override
Widget build(BuildContext context) {
// TODO: implement build
return Scaffold(
appBar: AppBar(
title: Text(this.arguments['id']),
),
body: Text(this.arguments['id']),
);
}
首先茅主,需要?jiǎng)?chuàng)建構(gòu)造函數(shù),在構(gòu)造函數(shù)里面設(shè)置參數(shù)傳遞的對(duì)象arguments土榴,另外诀姚,在交互代碼中獲取對(duì)應(yīng)的參數(shù)值