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