注意:点击顶部按钮时候会触犯_tabController.index会触发两次,普通左右滑动触发一次,所以为了避免触发两次,需要加如下判断
if (_tabController.animation!.value == _tabController.index) {print('${_tabController.animation!.value} --- ${_tabController.index}');
}
2.1 定义keepAliveWrapper.dart 文件;
import 'package:flutter/material.dart';class KeepAliveWrapper extends StatefulWidget {const KeepAliveWrapper({Key? key, @required this.child, this.keepAlive = true}): super(key: key);final Widget? child;final bool keepAlive;@overrideState createState() => _KeepAliveWrapperState();
}class _KeepAliveWrapperState extends Statewith AutomaticKeepAliveClientMixin {@overrideWidget build(BuildContext context) {return widget.child!;}@overridebool get wantKeepAlive => widget.keepAlive;@overridevoid didUpdateWidget(covariant KeepAliveWrapper oldWidget) {if (oldWidget.keepAlive != widget.keepAlive) {// keepAlive 状态需要更新,实现在 AutomaticKeepAliveClientMixin 中updateKeepAlive();super.didUpdateWidget(oldWidget);}}
}
// 引入你自己的路径 记得替换
import '../../util/keepAliveWrapper.dart'; // 引入你自己的路径 记得替换
// 要缓存数据的组件包起来
KeepAliveWrapper(child: Center(child: Text('标题$item内容。。。'),),
)
class _HomePageState extends State with SingleTickerProviderStateMixin{}
late TabController _tabController;
@overridevoid initState() {super.initState();_tabController = TabController(length: _lists.length, vsync: this); // 初始化长度_tabController.addListener(() {if (_tabController.animation!.value == _tabController.index) {print('${_tabController.animation!.value} --- ${_tabController.index}');}});}
git地址