大多数应用程序包含多个页面。例如,我们可能有一个显示产品的页面,然后,用户可以点击产品,跳到该产品的详情页。

在Android中,页面对应的是Activity,在iOS中是ViewController。而在Flutter中,页面只是一个widget!

在Flutter中,我们那么我们可以使用Navigator在页面之间跳转。

步骤

  1. 创建两个页面。
  2. 调用Navigator.push导航到第二个页面。
  3. 调用Navigator.pop返回第一个页面。

1. 创建两个页面

我们创建两个页面,每个页面包含一个按钮。点击第一个页面上的按钮将导航到第二个页面。点击第二个页面上的按钮将返回到第一个页面。页面结构如下:

  1. class FirstScreen extends StatelessWidget {
  2. @override
  3. Widget build(BuildContext context) {
  4. return new Scaffold(
  5. appBar: new AppBar(
  6. title: new Text('First Screen'),
  7. ),
  8. body: new Center(
  9. child: new RaisedButton(
  10. child: new Text('Launch new screen'),
  11. onPressed: () {
  12. // Navigate to second screen when tapped!
  13. },
  14. ),
  15. ),
  16. );
  17. }
  18. }
  19. class SecondScreen extends StatelessWidget {
  20. @override
  21. Widget build(BuildContext context) {
  22. return new Scaffold(
  23. appBar: new AppBar(
  24. title: new Text("Second Screen"),
  25. ),
  26. body: new Center(
  27. child: new RaisedButton(
  28. onPressed: () {
  29. // Navigate back to first screen when tapped!
  30. },
  31. child: new Text('Go back!'),
  32. ),
  33. ),
  34. );
  35. }
  36. }

2. 调用Navigator.push导航到第二个页面

为了导航到新的页面,我们需要调用Navigator.push方法。 该push方法将添加Route到由导航器管理的路由栈中!

push方法需要一个Route,但Route从哪里来?我们可以创建自己的,或直接使用MaterialPageRouteMaterialPageRoute很方便,因为它使用平台特定的动画跳转到新的页面(Android和IOS屏幕切换动画会不同)。

FirstScreen Widget的build方法中,我们添加onPressed回调:

  1. // Within the `FirstScreen` Widget
  2. onPressed: () {
  3. Navigator.push(
  4. context,
  5. new MaterialPageRoute(builder: (context) => new SecondScreen()),
  6. );
  7. }

3. 调用Navigator.pop返回第一个页面。

现在我们在第二个屏幕上,我们如何关闭它并返回到第一个屏幕?使用Navigator.pop方法! 该pop方法将Route从导航器管理的路由栈中移除当前路径。代码如下:

  1. // Within the SecondScreen Widget
  2. onPressed: () {
  3. Navigator.pop(context);
  4. }

完整的例子

  1. import 'package:flutter/material.dart';
  2. void main() {
  3. runApp(new MaterialApp(
  4. title: 'Navigation Basics',
  5. home: new FirstScreen(),
  6. ));
  7. }
  8. class FirstScreen extends StatelessWidget {
  9. @override
  10. Widget build(BuildContext context) {
  11. return new Scaffold(
  12. appBar: new AppBar(
  13. title: new Text('First Screen'),
  14. ),
  15. body: new Center(
  16. child: new RaisedButton(
  17. child: new Text('Launch new screen'),
  18. onPressed: () {
  19. Navigator.push(
  20. context,
  21. new MaterialPageRoute(builder: (context) => new SecondScreen()),
  22. );
  23. },
  24. ),
  25. ),
  26. );
  27. }
  28. }
  29. class SecondScreen extends StatelessWidget {
  30. @override
  31. Widget build(BuildContext context) {
  32. return new Scaffold(
  33. appBar: new AppBar(
  34. title: new Text("Second Screen"),
  35. ),
  36. body: new Center(
  37. child: new RaisedButton(
  38. onPressed: () {
  39. Navigator.pop(context);
  40. },
  41. child: new Text('Go back!'),
  42. ),
  43. ),
  44. );
  45. }
  46. }