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頁 );