2018-11-29 路由

Flutter有两种跳转方式:
静态路由,在创建时就已经明确知道了要跳转的页面和值
动态路由,跳转传入的目标地址和要传入的值都是动态的

//跳转的新页面
class newPage extends StatelessWidget {
  final String title;
  newPage(this.title);

  @override
    Widget build(BuildContext context) {
      // TODO: implement build
      return new Scaffold(
        appBar: AppBar(
          title: new Text('page2'),
        ),
        body: new Center(
          child: new Column(
            children: [
               new Text(
                title,
                style: new TextStyle(fontSize: 25),
              ),
              new RaisedButton(
                child: new Text('返回'),
                onPressed: () {
                  //pop时返回数据
                  Navigator.of(context).pop('返回数据:hello world');
                },
              )
            ],
          ),
        ),
      );
    }
}

// routes 是 MaterialApp 的定义路由的属性,是个map <目标路由的名称, 目标页面>
routes:  {
   '/newPage': (BuildContext context) => new newPage('hello'),
},

1.静态路由的方式跳转

Future future = Navigator.of(context).pushNamed('/newPage');

2.动态路由的方式跳转

Future future = Navigator.of(context).push(
  new PageRouteBuilder(
    pageBuilder: (BuildContext context, Animation animation, Animation secondaryAnimation) {
      return newPage('dynamic route page');
    }
  )
);

3.通过 Future 对象接受上个页面返回的数据

// 获取返回数据
future.then((onValue){
  showDialog(
    context: context,
    builder: (BuildContext context) {
      return AlertDialog(
        //弹出 “返回数据:hello world”
        content: new Text(onValue),
        actions: [
          FlatButton(
            child: new Text('done'),
            onPressed: () {
              Navigator.of(context).pop();
            },
          )
      ],);
    }
  );
});

小结:
使用 Navigator.of(context).pushNamed('/newPage'); 进行静态路由的跳转
使用 Navigator.of(context).push(route); 进行动态路由的跳转,动态路由可以传入未知数据
使用 Navigator.of(context).pop(); 可以进行路由的出栈
通过 Future 对象接受上个页面返回的数据

你可能感兴趣的:(2018-11-29 路由)