flutter功能
带缓存的tab切换功能
使用PageController进行对应tab的widget缓存
late PageController _keepActiveVC;///当前使用的视图索引late int _index;late PageController _keepActiveVC;/// 所有视图final List<Widget> _bodys = [];void initState() {super.initState();_index = 0;//页面控制器初始化_keepActiveVC = PageController(initialPage: _index );}- Widget build(BuildContext context) {return Scaffold(body: _body(), bottomNavigationBar: _buildNavigationBar());}BottomNavigationBar _buildNavigationBar() {BottomNavigationBar bar = MyBottomNavigationBar(......onTap: (i) {setState(() {_index = i;///切换tab是跳转页面_keepActiveVC.jumpToPage(_index);});},);return bar;}Widget _body() {return PageView(///禁用滚动physics: const NeverScrollableScrollPhysics(),controller: _keepActiveVC, //初始化的PageControllerchildren: _bodys, //当前所有视图的数组onPageChanged: (index) {_index = index; //切换选中的时候进行赋值},);
body中的子widget需要with AutomaticKeepAliveClientMixin,并返回wantKeepAlive为true;
class _MyView extends State<MyView> with AutomaticKeepAliveClientMixin{
...... bool get wantKeepAlive => widget.cacheWebView;
}
异常
Flutter 报错 setState() or markNeedsBuild() called during build
原因:视图未构建成功时调用了setState()或markNeedsBuild()方法
解决方法:
1.修改构建过程
2.使用官方提供了一个组件创建完成的回调通知方法
WidgetsBinding.instance.addPostFrameCallback((_) { //需要创建的小组件});