Flutter 路由 页面间跳转和传参 返回

Navigator

Navigator用来管理堆栈功能(即push和pop),在Flutter的情况下,当我们导航到另一个屏幕时,我们使用Navigator.push方法将新屏幕添加到堆栈的顶部。当然,这些pop方法会从堆栈中删除该屏幕。

在push的时候使用自定义方法构建一个路由

   Navigator.push(
        context, 
        MaterialPageRoute(builder:(context) => new InfoPage(product: products[index]))
   );

这种方式可以传递参数。

使用Navigator的pop返回可返回上一级,并携带一个参数

Navigator.pop(context,'携带参数'); 

push和pushNamed

push与pushNames运行效果相同,只是接口的调用方式不同, 都是将一个界面压入栈中. 区别在于, push是亲手把界面扔入栈中, 而pushNames则是通过点名的方式通过router让界面自己进入栈中

// push的调用方法
Navigator.push(context,  new MaterialPageRoute(
    builder: (context)  {
      return Scaffold(
        appBar: AppBar(
          title: Text('我是新的界面'),
        )
      );
    }
));

// pushNamed的调用方法
// 先在Router上定义Page;
routes: <String, WidgetBuilder> {
    '/xiaoming': (_) => new XiaoMingPage(),
}
...
Navigator.pushNamed(context, '/XiaoMingPage');

实例地址:https://www.cnblogs.com/joe235/p/11242354.html

 直接返回上上级 
Navigator.of(context)..pop()..pop();

替换路由:

比如A页面点击注册,跳到B页面,B页面点击下一步跳到C页面,C页面点击完成跳回A页面。

在B页面点击下一步的时候,使用替换路由跳到C页面,这时如果点击左上角返回按钮,直接返回到A页面。

Navigator.of(context).pushReplacementNamed('/registerSecond'); //替换路由

子页面向父级页面pop()传参

返回数据的方式:

Navigator.pop(context,'xxx'); //xxx就是返回的参数

pop()传参是当页面B返回到页面A时,页面A通过.then()接收,代码如下:

Navigator.push(
  context, 
  MaterialPageRoute(builder: (BuildContext context){
     return PageB(
       userName: '张三',
       userAge: '18岁',
     );
  })).then((userInfo){
    setState(() {
      backResult = userInfo;
    });
  });

在B页面中直接把需要传的参数放入pop()中即可,代码如下:

String userInfo = '对不起,今天已经打过卡了!';
Navigator.of(context).pop(userInfo);

直接返回根,主页面:

//表示把前面导航置为空,记得要引入IndexPage页
Navigator.of(context).pushAndRemoveUntil(
                new MaterialPageRoute(builder:(context) => new IndexPage()),
                (route) => route == null 
);

返回BottomNavigationBarItem指定页面:

首先要修改IndexPage页

class IndexPage extends StatefulWidget {
  final index; //增加index参数
  IndexPage({Key key,this.index = 0}) : super(key: key); //不传默认0

  _IndexPageState createState() => _IndexPageState(this.index);
}

class _IndexPageState extends State<IndexPage> {
   _IndexPageState(index){ //增加构造函数
     this.currentIndex = index;
  }

  //int currentIndex = 0; //当前索引
  int currentIndex; //当前索引

}

当前代码页:

//返回指定tab页
Navigator.of(context).pushAndRemoveUntil(
        new MaterialPageRoute(builder:(context) => new IndexPage(index:1)),
        (route) => route == null //表示把前面导航置为空,要引入IndexPage页
);
原文地址:https://www.cnblogs.com/joe235/p/11208576.html