最近學習用flutter做一個app,做首頁時用viewpage實現,後發現每次切換底部tab,頁面都會重繪。
隨即網上查了好多資料,基本上都是繼承AutomaticKeepAliveClientMixin,然後重寫wantKeepAlive = true;
實際做法就是:
class MainScreenState extends State<MainScreen> with AutomaticKeepAliveClientMixin
然後重寫:
@override bool get wantKeepAlive => true;
但是在我這裏並沒有起作用,具體原因有待查明。
然後發現了另外一種方法。
就是,不使用PageView 而是使用IndexedStack。
IndexedStack所有child的狀態都被保持,僅顯示指定頁面,其它頁面是不可見的。
使用IndexedStack後頁面也比PageView更簡潔了。
代碼如下:
int _selectedIndex = 0; // 當前選中的索引 /// tabs的名字 final bottomBarTitles = ["資訊", "方案", "排行", "我的"]; var pages = <Widget>[ HomeScreen(), PlanWidget(), ReportCardWidget(), MyWidget() ]; @override Widget build(BuildContext context) { // TODO: implement build return WillPopScope( onWillPop: _onWillPop, child: Scaffold( body: IndexedStack( index: _selectedIndex, children: pages, ), bottomNavigationBar: BottomNavigationBar( currentIndex: _selectedIndex, type: BottomNavigationBarType.fixed, // 設置顯示模式 items: <BottomNavigationBarItem>[ BottomNavigationBarItem( icon: Icon(Icons.art_track), title: Text(bottomBarTitles[0])), BottomNavigationBarItem( icon: Icon(Icons.videogame_asset), title: Text(bottomBarTitles[1])), BottomNavigationBarItem( icon: Icon(Icons.assessment), title: Text(bottomBarTitles[2])), BottomNavigationBarItem( icon: Icon(Icons.account_box), title: Text(bottomBarTitles[3])) ], onTap: (int index) { setState(() { _selectedIndex = index; }); }, ), ), ); }
完整代碼:https://github.com/YY-tomorrow/flutter_zjy
當然使用IndexedStack也是參考了一篇文章:https://www.jb51.net/article/157680.htm,還講述了一些其他的方法,個人採用了IndexedStack這種方式。