Flutter页面间跳转和传参Navigator的使用

Flutter中的默认导航分成两种,一种是命名的路由,一种是构建路由。

命名路由

(1)需要一开始在创建App时定义

1
2
3
4
5
6
new MaterialApp(
....
routes: {
"route-name": (BuildContext context) => new NewPage(),
},
);

(2)使用Navigator.pushNamed跳转

1
Navigator.pushNamed(context, "route-name");

缺点:不能传递参数

(3)接收路由返回的参数

1
2
3
Navigator.pushNamed<String>(context, "route-name").then((String value) {

});

注意push系列的方法返回值是一个Future,可以用来接收参数

构建路由

(1)Navigator.push构建路由跳转

1
2
3
Navigator.push(context, new MaterialPageRoute(builder: (BuildContext context){
return new PayPage(orderId: order['id'],);
}))

(2)传递参数并接收返回参数

1
2
3
4
5
6
7
8
9
Navigator.push(context, new MaterialPageRoute(builder: (BuildContext context) {
return CheckoutPage(cartList: checkedCartList,);
})).then((Object result) {
print("返回值: ${result.toString()}");
Map<String, dynamic> resultMap = result;
if (resultMap != null) {

}
});

(3)接收路由传递参数

1
2
3
4
5
6
7
class CheckoutPage extends BaseAuthPage {
List cartList;
CheckoutPage({Key key, this.cartList}) : super(key: key);

@override
State<StatefulWidget> createState() => new CheckoutPageState();
}

(4)返回上一页并携带参数

1
Navigator.of(context).pop({'address_update': true});

(5)路由跳转并销毁当前页面

1
2
3
4
5
6
7
8
9
Navigator.pushReplacement(context, new MaterialPageRoute(builder: (BuildContext context) {
return PayPage(orderId: orderId,);
})).then((Object result) {
print("返回值: ${result.toString()}");
Map<String, dynamic> resultMap = result;
if (resultMap != null) {

}
});

(6)路由跳转并销毁先前所有页面

1
2
3
4
5
6
Navigator.pushAndRemoveUntil(context, new MaterialPageRoute(builder: (BuildContext context) {
return MainPage(title: "传递的参数");
}), (route) => route == null).then((Object result) {

}
);

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2020 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :