最近学习用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这种方式。