简单 demo
- class _RankPageState extends State<RankPage>{
- final List<Tab> titleTabs = <Tab>[
- Tab(
- text: '今日实时榜',
- ),
- Tab(
- text: '昨日排行榜',
- ),
- Tab(
- text: '上周积分榜',
- ),
- ];
- ...
- child: Scaffold(
- appBar: AppBar(
- ...
- elevation: 0.0,
- backgroundColor: Color.fromRGBO(26, 172, 255, 1),
- title: TabBar(
- isScrollable: true,
- indicator: UnderlineTabIndicator(
- borderSide: BorderSide(style: BorderStyle.none)),
- tabs: titleTabs
- ),
- ),
- body: Container(
- color: Color.fromRGBO(26, 172, 255, 1),
- child: TabBarView(
- //TabBarView 默认支持手势滑动,若要禁止设置 NeverScrollableScrollPhysics
- physics: NeverScrollableScrollPhysics(),
- children: <Widget>[
- Center(child:Text('view1')),
- Center(child:Text('view2')),
- Center(child:Text('view3')),
- ],
- ),
- ),
- ),
- ...
- }
- 复制代码
TabBar与TabBarView通过index有一一对应关系,并且默认提供了DefaultTabController
建立两者之间的关系,若要切换动画以及监听切换交互,可以自定义一个 Controller
- class _RankPageState extends State<RankPage> with SingleTickerProviderStateMixin{
- ...
- TabController tabController;
- @override
- void initState() {
- super.initState();
- // 添加监听器
- tabController = TabController(vsync: this, length: titleTabs.length)
- ..addListener(() {
- switch (tabController.index) {
- case 0:
- print(1);
- break;
- case 1:
- print(2)
- break;
- case 2:
- print(3)
- break;
- }
- });
- }
- ...
- //增加controller
- title: TabBar(
- controller: tabController,
- ...
- )
- ...
- child: TabBarView(
- controller: tabController,
- ...
- )
- ...
- }
- 复制代码
运行之后查看结果,每次切换 tab 控制台都会打印相应的值,但有个问题,点击选项卡切换时打印了2次,似乎执行了两遍,滑动切换时正常输出一次。
原因大致是因为: 点击时 在动画过程先后触发了 notifyListeners();
源码如下:
看一下 TabController Class API,有以下属性
- //该动画值表示当前TabBar选中的指示器位置以及TabBar和TabBarView的scrollOffsets
- animation → Animation<double>
- //当前选中Tab的下标。改变index也会更新 previousIndex、设置animation's的value值、重置indexIsChanging为false并且通知监听器
- index ↔ int
- //true:当动画从上一个跳到下一个时
- indexIsChanging → bool
- //tabs的总数,通常大于1
- length → int
- //不同于animation's的value和index。offset value必须在-1.0和1.0之间
- offset ↔ double
- //上一个选中tab的index值,最初与index相同
- previousIndex → int
- 复制代码
那么我们可以加一层判断在监听器中
- ...
- tabController = TabController(vsync: this, length: titleTabs.length)
- ..addListener(() {
- if(tabController.indexIsChanging){
- switch (tabController.index) {
- case 0:
- print(1);
- break;
- case 1:
- print(2)
- break;
- case 2:
- print(3)
- break;
- }
- }
- });
- ...
- 复制代码
以上解决了点击执行两次代码块的问题,但试试滑动的时候,indexIsChanging一直都是false,也就是说滑动切换无法执行我们的代码。。。。
摸索调试了一番,为了让滑动和点击都执行我们的代码块且只有一次,做如下改动
- ...
- tabController = TabController(vsync: this, length: titleTabs.length)
- ..addListener(() {
- if(tabController.index.toDouble() == tabController.animation.value){
- switch (tabController.index) {
- case 0:
- print(1);
- break;
- case 1:
- print(2)
- break;
- case 2:
- print(3)
- break;
- }
- }
- });
- ...
- 复制代码
恩~~~解决我们的需求了。。。