flutter中使用动态路由传递参数的封装案例,子组件页面只需要接收arguments参数即可,参数是一个map,里面包含有所需要的参数,类似于json。在MaterialApp中配置onGenerateRoute,然后动态判断传递参数:
routes列表:
// 命名路由传参
Map routes = {
"/home": (content) => Home(),
"/search": (context) => SearchPage(),
// 传递参数的形式
"/store": (context, {arguments}) => Store(arguments: arguments)
};
onGenerateRoute函数:
onGenerateRoute: (RouteSettings settings) {
// 获取声明的路由页面函数
var pageBuilder = routes[settings.name];
if (pageBuilder != null) {
if (settings.arguments != null) {
// 创建路由页面并携带参数
return MaterialPageRoute(
builder: (context) =>
pageBuilder(context, arguments: settings.arguments));
} else {
return MaterialPageRoute(
builder: (context) => pageBuilder(context));
}
}
return MaterialPageRoute(builder: (context) => HomePage());
}
然后在路由跳转的时候, 使用pushNamed进行传递参数:
Navigator.pushNamed(context, "/store",
arguments: {"title": "京东首页", "price": 100});
在子组件里面,定义并接收参数:
import "package:flutter/material.dart";
class Store extends StatefulWidget {
const Store({super.key, this.arguments});
final dynamic arguments;
@override
State<Store> createState() => _StoreState();
}
class _StoreState extends State<Store> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(
"${widget.arguments != null ? widget.arguments['title'] : "ThirdPage"}"),
),
body: Center(
child: ElevatedButton(
child: Text("返回上一家"),
onPressed: () {
print("返回上一家");
Navigator.pop(context);
},
),
),
);
}
}
最后的优化,可以将route封装成一个dart包,然后引入到materialApp中,让逻辑更清晰:
router.dart源代码:
import "package:flutter/material.dart";
import "../main.dart";
import "../pages/home.dart";
import "../pages/search.dart";
import "../pages/store.dart";
// 命名路由传参
Map routes = {
"/home": (content) => Home(),
"/search": (context) => SearchPage(),
"/store": (context, {arguments}) => Store(arguments: arguments)
};
// 定义一个函数,并返回MaterialPageRoute
var onGenerateRoute = (RouteSettings settings) {
var pageBuilder = routes[settings.name];
if (pageBuilder != null) {
if (settings.arguments != null) {
// 创建路由页面并携带参数
return MaterialPageRoute(
builder: (context) =>
pageBuilder(context, arguments: settings.arguments));
} else {
return MaterialPageRoute(builder: (context) => pageBuilder(context));
}
}
return MaterialPageRoute(builder: (context) => HomePage());
};
在materialApp中引入:
最后的效果图: