【Android】Flutter TabBar 切换Tab时文字抖动

549 阅读1分钟

1.gif

解决办法

如上图所示抖动,只需要一行代码就能解决。
给TabController添加一个动画时间就可以了。

animationDuration: const Duration(milliseconds: 50),

//  添加 animationDuration: const Duration(milliseconds: 50)
 DefaultTabController(
          animationDuration: const Duration(milliseconds: 50),
          length: _tabs.length,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              TabBar(
                tabs: _tabs,
                isScrollable: true,
                tabAlignment: TabAlignment.start,
                indicatorColor: Colors.red,
                indicatorSize: TabBarIndicatorSize.tab,
                indicatorPadding: EdgeInsets.only(left: 20.w, right: 55.w),
                labelPadding: EdgeInsets.only(left: 20.w, right: 20.w),
                labelColor: GColors.primary,
                labelStyle:
                    TextStyle(fontSize: 18.sp, fontWeight: FontWeight.bold),
                unselectedLabelStyle:
                    TextStyle(fontSize: 14.sp, fontWeight: FontWeight.normal),
              ),
              Expanded(child: TabBarView(children: [Container(), Container()]))
            ],
          ),
        )

效果如下:

原因

通过查看TabController的源码发现,tab切换的默认动画是300毫秒。

我们切换tab时, 在300毫秒内执行了字体在从14过渡到18的动画,我们会看到明显的抖动效果。
如果我们切换tab时,字体大小设置为14过渡到25时或者更大,我们会发现抖动效果消失了。在相同的时间里,大小差值越大,我们看到的动画变化更快也就更平滑,所以我们也看不到抖动了。现在我们想大小差值不变,抖动消失,只需要减少动画时间就可以了!