Flutter中的路由

前言

路由是native中应用的比较多,特别是组件化的工程中,更是用来解耦的利器,比较常用的有阿里的ARouter等,路由这一思想也是借鉴前端而来,比如web中页面跳转就是一个url就到了一个新的页面,Flutter既然是新一代的跨端方案,而且从RN借鉴了不少思想,路由当然也是必不可少的,本篇将了解下Flutter的路由

同步更新gitpage xsfelvis.github.io/2018/12/15/…

Flutter的路由

在Flutter中支持所有路由场景,push、pop页面,页面间的参数传递等等。flutter里面的路由可以分成两种,

  • 一种是直接注册,不能传递参数,可以称 为静态路由
  • 一种要自己构造实例,可以传递参数,可以称为 动态路由。

静态路由

创建时就已经明确知道了要跳转的页面和值,在新建一个MD风格的App的时候,可以传入一个routes参数来定义路由。但是这里定义的路由是静态的,它不可以向下一个页面传递参数

@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");
  },
)
复制代码

动态路由

当需要向下一个页面传递参数时,要用到所谓的动态路由,自己生成页面对象,所以可以传递自己想要的参数。

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来接收

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压入路由和弹出路由

入栈:

  • 使用Navigator.of(context).pushName(“path“)或者Navigator.pushName(context,“path“)可以进行静态路由的跳转前提是需要在route属性里面注册
  • 使用push(Route)可以进行态路由的跳转,动态路由可以传入未知数据

出栈

  • 使用pop()可以进行路由的出栈并且可以传递参数
  • 可以使用Future接收上个页面返回的值。

代码在 github.com/xsfelvis/le…

猜你喜欢

转载自juejin.im/post/5c14a2e0e51d454827178e0e