flutter刷新页面_Flutter BottomNavigationBar切换会刷新当前页面解决方
問題描述
BottomNavigationBar?是flutter 中最常用的UI組建,剛接觸時(shí)發(fā)現(xiàn)在切換tab 的時(shí)候,會(huì)刷新當(dāng)前的所有狀態(tài),每個(gè)頁面都會(huì)重新刷新。于是乎,在這里先記錄下解決方案。
BottomNavigationBar基本代碼
以下Home 是首頁,切入三個(gè)tab,代碼如下:
class Home extends StatefulWidget { @override createState() => _Home();}class _Home extends State { int _currentIndex = 0; List _pages; @override void initState() { _pages = [ new Guild(), new ActivityList(), new Mine(), ]; super.initState(); } @override void dispose() { super.dispose(); _pageController.dispose(); } var _pageController = PageController(); @override Widget build(BuildContext context) { return Scaffold( body: PageView.builder( controller: _pageController, physics: NeverScrollableScrollPhysics(), onPageChanged: _pageChanged, itemCount: _pages.length, itemBuilder: (context, index) => _pages[index]), bottomNavigationBar: BottomNavigationBar( currentIndex: _currentIndex, fixedColor: Colors.black,//點(diǎn)擊選擇 type: BottomNavigationBarType.shifting, onTap: onTabTapped, items: [ BottomNavigationBarItem( //backgroundColor: Theme.of(context).appBarTheme.color icon: Icon(Icons.home), title: Text("公會(huì)"), backgroundColor: Theme.of(context).appBarTheme.color), BottomNavigationBarItem( icon: Icon(Icons.notifications), title: Text("活動(dòng)"), backgroundColor: Theme.of(context).appBarTheme.color), BottomNavigationBarItem( icon: Icon(Icons.person), title: Text("我的"), backgroundColor: Theme.of(context).appBarTheme.color), ], ), ); } void _pageChanged(int index) { setState(() { if (_currentIndex != index) _currentIndex = index; }); } void onTabTapped(int index) { _pageController.jumpToPage(index); }}
這樣像簡(jiǎn)單的寫,其實(shí)就會(huì)出現(xiàn) 切換tab 的時(shí)候,重新刷新當(dāng)前頁面的現(xiàn)象,之前保留的狀態(tài)就會(huì)消失。
解決方案
解決方案分為四個(gè)步驟(以下我將其中一個(gè)頁面名字叫做:DemoPage):
第一步將tab里面的頁面DemoPage需要實(shí)現(xiàn) AutomaticKeepAliveClientMixin
第二步設(shè)置DemoPage實(shí)現(xiàn)代碼bool get wantKeepAlive => true;
第三步DemoPage里面實(shí)現(xiàn)Widget build(BuildContext context)調(diào)用super.build(context);
第四步PageView.builder 設(shè)置NeverScrollableScrollPhysics(),//禁止頁面左右滑動(dòng)切換 (可選,好像這部不設(shè)置也沒關(guān)系,具體看實(shí)際情況來)
具體 代碼如下:
1、class _DemoPageState extends State with AutomaticKeepAliveClientMixin{//要點(diǎn)1
2、 @override
bool get wantKeepAlive => true;//要點(diǎn)2
3、@override
Widget build(BuildContext context) {
super.build(context);//要點(diǎn)3
4、使用PageView構(gòu)建
PageView.builder(//要點(diǎn)1
physics: NeverScrollableScrollPhysics(),//禁止頁面左右滑動(dòng)切換
controller: _pageController,
onPageChanged: _pageChanged,//回調(diào)函數(shù)
itemCount: _pages.length,
itemBuilder: (context,index)=>_pages[index]
)
參看文獻(xiàn):
來源:https://www.cnblogs.com/kingbo/p/11430351.html
總結(jié)
以上是生活随笔為你收集整理的flutter刷新页面_Flutter BottomNavigationBar切换会刷新当前页面解决方的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 机器人石材雕刻机_一种石材雕刻机器人的制
- 下一篇: k8s和harbor的集成_爱威尔-基于