返回到上一級頁面
Navigator.of(context).pop();
原理:不清除路由路徑(路由棧),保存所有的路由過程
需求:
- 正常返回上一頁面
替換路由
原理:每跳轉一個路由便清除上一路由頁面,所以操作到最後一步返回時直接到首頁。
需求:
- 我們從首頁面跳轉到了 registerFirst 頁面
- 然後從 registerFirst 頁面通過
pushReplacementNamed
跳轉到了 registerSecond 頁面 - 這個時候當我們點擊 registerSecond 的返回按鈕的時候它會直接返回到用戶中心
Navigator
.of(context)
.pushReplacementNamed('/registerSecond');
返回到根路由
原理:清除所有路由頁面,直接跳轉到首頁
需求:
- 我們從首頁跳轉到 registerFirst 頁面
- 然後從 registerFirst 頁面跳轉到 registerSecond 頁面
- 再然後從 registerSecond 跳轉到了 registerThird 頁面。
- 這個時候我們想的是 registerThird 註冊成功後返回到用戶中心。
Navigator
.of(context)
.pushAndRemoveUntil(
//這裏的Tabs()就是引入的跟路由頁面
new MaterialPageRoute(builder: (context) => new Tabs()),
)
);
從哪來回哪去?
原理:還是一樣使用返回根路由,邏輯中操作你所要跳轉的頁面。
需求:
- 我們從用戶中心跳轉到 registerFirst 頁面
- 然後從 registerFirst 頁面跳轉到 registerSecond 頁面
- 再然後從 registerSecond 跳轉到了 registerThird 頁面。
- 這個時候我們想的是 registerThird 註冊成功後返回到用戶中心。
Navigator
.of(context)
.pushAndRemoveUntil(
//不操作會直接返回到首頁,包括tabBar
//參數傳遞,index=1 就是首頁,每一個索引對應的是tabBar的不同頁面 ,比如 2 就是用戶中心
new MaterialPageRoute(builder: (context) => new Tabs(index:2)),
)
);
Tabs()
頁面示例代碼
import 'package:flutter/material.dart';
import 'HomePage.dart';
import 'Payment.dart';
import 'People.dart';
class HomePageSet extends StatefulWidget {
final index;//定義常量以及下面的可選參數並且設置默認值
HomePageSet({Key key,this.index=0}) : super(key: key);
@override
_HomePageSetState createState() => _HomePageSetState(this.index);
}
class _HomePageSetState extends State<HomePageSet> {
int curIndex = 0;//定義接收並且賦值
_HomePageSetState(index){
this.curIndex = index;
}
List PageList = [
HomePage(),
Payment(),
People(),
];
@override
Widget build(BuildContext context) {
return Container(
child: Scaffold(
appBar: AppBar(
title: Text("StatefulWidget,BottomNavigationBar"),
),
body: this.PageList[this.curIndex],
bottomNavigationBar: BottomNavigationBar(
currentIndex: curIndex,
onTap: (int index) {//底佈菜單通過這裏的索引來設置是否選中
print(index);
setState(() {//動態設置頁面索引
this.curIndex = index;
});
},
iconSize: 40,
fixedColor: Colors.orange,
type: BottomNavigationBarType.fixed,
//配置多個底佈菜單
items: [
BottomNavigationBarItem(
icon: Icon(Icons.home), title: Text("首頁")),
BottomNavigationBarItem(
icon: Icon(Icons.payment), title: Text("推薦")),
BottomNavigationBarItem(
icon: Icon(Icons.people), title: Text("用戶中心")),
]),
),
);
}
}