我們在開發(fā)的時候用底部導(dǎo)航欄是很常見的仁卷,flutter給我們默認(rèn)帶了bottomNavigationBar襟己,但是發(fā)現(xiàn)你直接這樣寫的時候,點擊導(dǎo)航欄切換組建的時候型宙,每次都會刷新狀態(tài),這用戶體驗是很不好的伦吠,今天給大家一種效率超高的解決方案妆兑,就是用PageView+AutomaticKeepAliveClientMixin組合實現(xiàn)狀態(tài)保存,切換組件的時候不刷新毛仪。
image
1.首先在有bottomNavigationBar的組件中加入pageview
/*
* 存儲的四個頁面搁嗓,和android 中的 Fragment一樣
*/
var _pages;
void initData() {
_pages = [
new WebPage(),
new DiscoverPage(),
new UserPage(),
];
}
PageView.builder(
//要點1
physics: NeverScrollableScrollPhysics(),
//禁止頁面左右滑動切換
controller: _pageController,
onPageChanged: _pageChanged,
//回調(diào)函數(shù)
itemCount: _pages.length,
itemBuilder: (context, index) => _pages[index]),
image
全部的代碼
class MainPage extends StatefulWidget {
@override
_MainPageState createState() => _MainPageState();
}
class _MainPageState extends State<MainPage> {
int _tabIndex = 0;
var tabImages;
var appBarTitles = ['首頁', '發(fā)現(xiàn)', '我的'];
var _pageController = PageController();
Text getTabTitle(int curIndex) {
if (curIndex == _tabIndex) {
return new Text(appBarTitles[curIndex]);
} else {
return new Text(appBarTitles[curIndex]);
}
}
/*
* 存儲的四個頁面,和Fragment一樣
*/
var _pages;
void initData() {
_pages = [
new WebPage(),
new DiscoverPage(),
new UserPage(),
];
}
@override
Widget build(BuildContext context) {
initData();
return Scaffold(
body: SafeArea(
child: PageView.builder(
//要點1
physics: NeverScrollableScrollPhysics(),
//禁止頁面左右滑動切換
controller: _pageController,
onPageChanged: _pageChanged,
//回調(diào)函數(shù)
itemCount: _pages.length,
itemBuilder: (context, index) => _pages[index]),
),
bottomNavigationBar: new BottomNavigationBar(
items: <BottomNavigationBarItem>[
new BottomNavigationBarItem(
icon: Icon(IconData(0xe71a, fontFamily: "iconfont")),
title: getTabTitle(0)),
new BottomNavigationBarItem(
icon: Icon(IconData(0xe746, fontFamily: "iconfont")),
title: getTabTitle(1)),
new BottomNavigationBarItem(
icon: Icon(IconData(0xe636, fontFamily: "iconfont")),
title: getTabTitle(2)),
],
type: BottomNavigationBarType.fixed,
fixedColor: Colors.green,
currentIndex: _tabIndex,
onTap: (index) {
print('onTap');
_pageController.jumpToPage(index);
},
),
);
}
void _pageChanged(int index) {
print('_pageChanged');
setState(() {
if (_tabIndex != index) _tabIndex = index;
});
}
}
這個時候我們發(fā)現(xiàn)頁面可以切換了箱靴,但是狀態(tài)還是沒有保存下來腺逛,接下來我們要修改其他的組件了。
2.在組件中實現(xiàn)AutomaticKeepAliveClientMixin
讓我們的state實現(xiàn)with AutomaticKeepAliveClientMixin衡怀,必須要重寫一個方法
@override
bool get wantKeepAlive => true;
image
這兩個必須要組合使用棍矛,才能實現(xiàn)保存狀態(tài)不刷新,每個需要保存狀態(tài)的組件都要with AutomaticKeepAliveClientMixin抛杨。