首发于个人公众号前端
Flutter中消息传递java
路由是native中应用的比较多,特别是组件化的工程中,更是用来解耦的利器,比较经常使用的有阿里的ARouter等,路由这一思想也是借鉴前端而来,好比web中页面跳转就是一个url就到了一个新的页面,Flutter既然是新一代的跨端方案,并且从RN借鉴了很多思想,路由固然也是必不可少的,本篇将了解下Flutter的路由git
同步更新gitpage xsfelvis.github.io/2018/12/15/…github
在Flutter中支持全部路由场景,push、pop页面,页面间的参数传递等等。flutter里面的路由能够分红两种,web
在建立时就已经明确知道了要跳转的页面和值,在新建一个MD风格的App的时候,能够传入一个routes参数来定义路由。可是这里定义的路由是静态的,它不能够向下一个页面传递参数ide
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
theme: new ThemeData(
primarySwatch: Colors.blue,
),
//注册路由表
routes: {
"router/static_page": (context) => StaticRoute(),
},
home: new MyHomePage(title: 'Flutter Demo Home Page'),
);
}
复制代码
经过routes这个属性注册好跳转的页面即key-value,上面的代码中组件化
key:router/static_page value: StaticRouter 而后使用的时候使用学习
FlatButton(
child: Text("open static router"),
textColor: Colors.blue,
onPressed: () {
Navigator.pushNamed(context, "router/static_page");
},
)
复制代码
当须要向下一个页面传递参数时,要用到所谓的动态路由,本身生成页面对象,因此能够传递本身想要的参数。ui
FlatButton(
child: Text("open dynamic router"),
textColor: Colors.blue,
onPressed: () {
Navigator.push(context, MaterialPageRoute(
builder: (context) {
return new EchoRoute("传入跳转参数");
}));
或者
Navigator.of((context).push(MaterialPageRoute(
builder: (context) {
return new EchoRoute("传入跳转参数");
}));
},
)
复制代码
new RaisedButton(
child: new Text("点我返回"),
onPressed: () {
Navigator.of(context).pop();
},
color: Colors.blue,
highlightColor: Colors.lightBlue,
)
复制代码
咱们能够在前一个页面接受第二个页面的返回值 在第一个页面跳转时候加上futrue来接收url
FlatButton(
child: Text("open dynamic router"),
textColor: Colors.blue,
onPressed: () {
Future future = Navigator.push(context,
MaterialPageRoute(builder: (context) {
return new EchoRoute("传入跳转参数");
}));
//接收动态页面返回时传回的值
future.then((value) {
showDialog(
context: context,
child: new AlertDialog(
title: new Text(value),
));
});
},
复制代码
在EchoRoute页面 返回时使用带参数的pop方法
new RaisedButton(
child: new Text("点我返回"),
onPressed: () {
// Navigator.of(context).pop();
Navigator.of(context).pop("我是来自dymamic 关闭的返回值");
},
color: Colors.blue,
highlightColor: Colors.lightBlue,
)
复制代码
这样就会在关闭EchoRoute回到跳转前页面时弹出dialog收到EchoRoute传来的参数
Navigator的职责是负责管理Route的,管理方式就是利用一个栈不停压入弹出,固然也能够直接替换其中某一个Route。而Route做为一个管理单元,主要负责建立对应的界面,响应Navigator压入路由和弹出路由
入栈:
出栈
欢迎关注个人公众号,一块儿学习,共同提升~
复制代码