Flutter中TabBar切換各Pag的狀態被重置

在Flutter裏BottomNavigationBar、TabBar、還有Drawer,你就會發現,在切換頁面之後,由於Widget的重繪,再返回原來的頁面時狀態丟失。

解決方法:

1、如果body 使用PageView包裝,然後在各子 List<Widget> 裏 實現AutomaticKeepAliveClientMixin類 裏的 wantKeepAlive 返回 true ;

///add 
final pageController = PageController();

////TableBar裏用的是PageView

return Scaffold(
      body: PageView(
        children: pages,
        controller: pageController,
        onPageChanged: (int index){
          setState(() {
            _selectedItem = index%3;
          });
        },
      ),

      bottomNavigationBar: BottomNavigationBar(
        backgroundColor: Colors.white,
        items: [
          _getBottomNavBarItem(Icons.home, "首頁", _barColor(0,context)),
          _getBottomNavBarItem(Icons.video_library, "視頻", _barColor(1,context)),
          _getBottomNavBarItem(Icons.person, "我的", _barColor(2,context)),
        ],

        currentIndex: _selectedItem,
         onTap:(int index){
//          setState(() {
//            _selectedItem = index;
//          }
//          );
          pageController.jumpToPage(index);
        },
      ),
    );

eg :首頁裏的處理

/// 1、 State 裏 混入 AutomaticKeepAliveClientMixin
class HomeState extends State <HomePage> with AutomaticKeepAliveClientMixin 

///2. 實現wantKeepAlive 返回 true 
 @override
  bool get wantKeepAlive => true;

2、不使用PageView 。在TabBar的body裏用IndexedStack包裝一下

Scaffold(
      body: IndexedStack(
        index: _selectedItem,
        children:pages,
      ),
      bottomNavigationBar: BottomNavigationBar(
      	backgroundColor: Colors.white,
        items: [
          _getBottomNavBarItem(Icons.home, "首頁", _barColor(0,context)),
          _getBottomNavBarItem(Icons.video_library, "視頻", _barColor(1,context)),
          _getBottomNavBarItem(Icons.person, "我的", _barColor(2,context)),
        ],
        currentIndex: _selectedItem,
        onTap:(int index){
          setState(() {
            _selectedItem = index;
          }
          );
        },
        )
  );

也可以很優雅的解決此問題。

後續

但是 !!!----------------------------重點的事情我要找下存在感!------------------------

使用IndexedStack 會使得 build 方法調用茫茫多次有沒有?這個真的很難忍受。

而使用PagView 則是正常的調用,所以還是建議小夥伴們用PagView吧。

參考 :StackOverflow

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章