Flutter系列(六) 中如何跳转界面

您好,欢迎关注我,本篇文章是关于 Flutter 的系列文,从简单的 Flutter 介绍开始,一步步带你了解进入 Flutter 的世界。你最好有一定的移动开发经验,如果没有也不要担心,在我的专栏底部给我留言,我会尽我的能力给你解答。

上一篇专栏,我带大家用Flutter实现了一个完整的可自定义配置的 PageView 指示器。这篇专栏,我会教大家在Flutter中如何实现界面跳转

在Android中,我们会使用Intent来进行界面间的跳转,用startActivityForResult来处理界面跳转完成后的回调;在iOS中,我们使用Pages进行页面跳转。

页面跳转

在Flutter中页面跳转方式有两种:

方法一:
直接跳转

Navigator.push(context, new MaterialPageRoute(builder: (context) => new SecondScreen()),);

方法二:
通过路由跳转

void main() {
  runApp(MaterialApp(
    home: MyAppHome(), // becomes the route named '/'
    routes: <String, WidgetBuilder> {
      '/a': (BuildContext context) => MyPage(title: 'page A'),
      '/b': (BuildContext context) => MyPage(title: 'page B'),
      '/c': (BuildContext context) => MyPage(title: 'page C'),
    },
  ));
}

Navigator.of(context).pushNamed('/b');

根据Flutter的文档,routes的灵感来源于reactjs,routes可以翻译为路由,可以看到这种routes的思路在目前的设计中彼此借鉴,routes的思路不仅在前端流行,比如在vue、reactjs、Angular中用到,而且在后端应用中也非常成熟。

关闭页面

使用Navigator.pop()方法可以直接

Navigator.pop(context);

也可以直接带参数回调。

Navigator.of(context).pop({"lat":43.821757,"long":-79.226392});

利用第三方库实现页面传值

Fluro是一个基于Flutter的路由传参库,它可以通过url传递参数。

new Container(
              height: 30.0,
              color: Colors.blue,
              child:new FlatButton(
                child: const Text('传递帐号密码'),
                onPressed: () {
                  var bodyJson = '{"user":1281,"pass":3041}';
                  router.navigateTo(context, '/home/$bodyJson');
                  // Perform some action
                },
              )),
          );

接收

class Home extends StatefulWidget{
  final String _result;
  Home(this._result);
    @override
  createState() => new HomeState();
}

class HomeState extends State<Home>{
  @override
  Widget build(BuildContext context) {
    return new Center(
      child: new Scaffold(
        appBar: new AppBar(
          title: new Text("个人主页"),
        ),
        body:new Center(child:  new Text(widget._result)),
      )
    );
  }

总结
本文介绍了Flutter中如何进行界面跳转,下一篇专栏我会教大家如何发布Flutter代码到公共库。

猜你喜欢

转载自blog.51cto.com/14295695/2414326