日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

flutter刷新页面_Flutter BottomNavigationBar切换会刷新当前页面解决方

發布時間:2025/3/20 编程问答 18 豆豆
生活随笔 收集整理的這篇文章主要介紹了 flutter刷新页面_Flutter BottomNavigationBar切换会刷新当前页面解决方 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

問題描述

BottomNavigationBar?是flutter 中最常用的UI組建,剛接觸時發現在切換tab 的時候,會刷新當前的所有狀態,每個頁面都會重新刷新。于是乎,在這里先記錄下解決方案。

BottomNavigationBar基本代碼

以下Home 是首頁,切入三個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,//點擊選擇 type: BottomNavigationBarType.shifting, onTap: onTabTapped, items: [ BottomNavigationBarItem( //backgroundColor: Theme.of(context).appBarTheme.color icon: Icon(Icons.home), title: Text("公會"), backgroundColor: Theme.of(context).appBarTheme.color), BottomNavigationBarItem( icon: Icon(Icons.notifications), title: Text("活動"), 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); }}

這樣像簡單的寫,其實就會出現 切換tab 的時候,重新刷新當前頁面的現象,之前保留的狀態就會消失。

解決方案

解決方案分為四個步驟(以下我將其中一個頁面名字叫做:DemoPage):

第一步將tab里面的頁面DemoPage需要實現 AutomaticKeepAliveClientMixin

第二步設置DemoPage實現代碼bool get wantKeepAlive => true;

第三步DemoPage里面實現Widget build(BuildContext context)調用super.build(context);

第四步PageView.builder 設置NeverScrollableScrollPhysics(),//禁止頁面左右滑動切換 (可選,好像這部不設置也沒關系,具體看實際情況來)

具體 代碼如下:

1、class _DemoPageState extends State with AutomaticKeepAliveClientMixin{//要點1

2、 @override

bool get wantKeepAlive => true;//要點2

3、@override

Widget build(BuildContext context) {

super.build(context);//要點3

4、使用PageView構建

PageView.builder(//要點1

physics: NeverScrollableScrollPhysics(),//禁止頁面左右滑動切換

controller: _pageController,

onPageChanged: _pageChanged,//回調函數

itemCount: _pages.length,

itemBuilder: (context,index)=>_pages[index]

)

參看文獻:

來源:https://www.cnblogs.com/kingbo/p/11430351.html

總結

以上是生活随笔為你收集整理的flutter刷新页面_Flutter BottomNavigationBar切换会刷新当前页面解决方的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。