flutter 使用命名的路由传递
2023-07-25 本文已影响0人
别看后面有人
全是学习和搬砖,只为记录部分代码,写项目的时候可以翻看一下
注意事项:使用命名路由的话body部分不能和routes同时存在,可以把body部分放在根部路由 "/"下面
另外如果有带参数的路由的话需要onGenerateRoute获取路由,
pageContentBuilder中的参数arguments 必须和routes中写的一致,不一致会报如图错误*
void main(){
runApp(MyApp());
}
class MyApp extends StatelessWidget {
MyApp({Key? key});
Map routes={
"/":(context)=>RouteNameDemo(),
"/page":(context)=>DemoPage(),
"/two":(context,{arguments})=>TwoRoute2(args: arguments,)
};
@override
Widget build(BuildContext context) {
return MaterialApp(
title: "命名路由",
// routes: {
// "/":(context)=>RouteNameDemo(),
// "/page":(context)=>DemoPage(),
// "/two":(context,{args})=>TwoRoute2(args: args,)
// },
initialRoute: "/",
onGenerateRoute: (RouteSettings settings){
//统一处理
final String? name=settings.name;
final Function? pageContentBuilder=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;
}
}
return null;
},
);
}
}
class RouteNameDemo extends StatelessWidget {
const RouteNameDemo({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("命名路由"),
),
body: ListView(
children: [
TextButton(
onPressed: (){
Navigator.of(context).pushNamed("/page");
},
child: Text("跳转"),
),
TextButton(
onPressed: () async {
await Navigator.of(context).pushNamed("/two",arguments: {
"name":"张三",
"name1":"张三1",
"name2":"张三2",
"name3":"张三3",
});
},
child: Text("跳转带参数"),
)
],
)
);
}
}
9d265b20f014c8bf9d4a477068f9dba9.jpg
接收页面的代码:
class TwoRoute2 extends StatelessWidget {
final Map args;
const TwoRoute2({Key? key, required this.args});
List<Widget> _getListData(){
List<Widget> data=[];
for(String str in args.values.toList()){
data.add(ListTile(
title: Text(str),
));
}
return data;
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("第二个页面"),
),
body: Scaffold(
appBar: AppBar(
title: const Text("路由"),
),
body: ListView(
children:_getListData(),
),
)
);
}
}