一、简介
很多时候,在路由跳转时我们需要带一些参数,比如打开商品详情页时,我们需要带一个商品id,这样商品详情页才知道展示哪个商品信息;又比如我们在填写订单时需要选择收货地址,打开地址选择页并选择地址后,可以将用户选择的地址返回到订单页等等。下面我们通过一个简单的示例来演示新旧路由如何传参。
需要说明:
1、“我是提示xxxx”是通过TipRoute
的text
参数传递给TipRoute
路由页的。我们可以通过等待Navigator.push(…)
返回的 Future 来获取新路由的返回数据。
2、在TipRoute
页中有两种方式可以返回到上一页;第一种方式是直接点击导航栏返回箭头,第二种方式是点击页面中的“返回”按钮。这两种返回方式的区别是前者不会返回数据给上一个路由,而后者会。下面是分别点击页面中的返回按钮和导航栏返回箭头后,RouterTestRoute
页中 print 方法在控制台输出的内容:
I/flutter (27896): 路由返回值: 我是返回值
I/flutter (27896): 路由返回值: null
示例:
class InfiniteListView extends StatefulWidget {
const InfiniteListView({Key? key}) : super(key: key);
@override
_InfiniteListViewState createState() => _InfiniteListViewState();
}
class _InfiniteListViewState extends State<InfiniteListView> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: ElevatedButton(
onPressed: () async {
// 打开`TipRoute`,并等待返回结果
var result = await Navigator.push( // 还有一种 Navigator.of(context).push的写法
context,
MaterialPageRoute(builder: (context) {
return const TipRoute(
// 路由参数
text: "我是提示xxxx",
);
},
),
);
//输出`TipRoute`路由返回结果
print("路由返回值: $result");
},
child: const Text("打开提示页"),
)
)
);
}
}
class TipRoute extends StatelessWidget {
const TipRoute({
Key? key,
required this.text, // 接收一个text参数
}) : super(key: key);
final String text;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("提示"),
),
body: Padding(
padding: const EdgeInsets.all(18),
child: Center(
child: Column(
children: <Widget>[
Text(text),
ElevatedButton(
onPressed: () => Navigator.pop(context, "我是返回值"), // 还有一种 Navigator.of(context).pop的写法
child: const Text("返回"),
)
],
),
),
),
);
}
}
上面介绍的是非命名路由的传值方式,命名路由的传值方式会有所不同,我们会在后面介绍。
网友评论