美文网首页
Flutter TabBar 文字抖动问题最简单的解决方案

Flutter TabBar 文字抖动问题最简单的解决方案

作者: 刘厚智 | 来源:发表于2019-06-20 17:58 被阅读0次

在解决这个问题时我详细阅读了另一个解决方案 从源码分析TabBar的文字抖动问题 对于新手来说不建议去修改Flutter的源码,我尝试不修改源码的解决方案,超级简单。

问题出现在这里,我们通过TabBar的这两个属性来实现选中时字体大一些。这样做文字会抖动。

    labelStyle: TextStyle(fontSize: 20.0),
    unselectedLabelStyle: TextStyle(fontSize: 16.0),

解决方案:
不使用这两个参数把他注释掉,然后把Tabbar放在使用 StatefulWidget 部件下,我们自己通过部件的刷新来实现切换文字变大的效果就可以解决抖动问题。 下面直接上源码。

class CommonWidgetTabBar extends StatefulWidget {
  @override
  _CommonWidgetTabBarState createState() => _CommonWidgetTabBarState();
}

class _CommonWidgetTabBarState extends State<CommonWidgetTabBar> {
  int tabIndex = 0;  // 当前选中索引
  @override
  Widget build(BuildContext context) {
    return TabBar(
      onTap: (index){
        // 每当TabBar 切换更新索引
        setState(() {
          tabIndex = index;
        });
      },
      isScrollable: true, // 是否滚动
      unselectedLabelColor: Colors.black54, //未选中颜色
      labelColor: Colors.blue, //选中颜色
      // labelStyle: TextStyle(fontSize: 20.0),
      // unselectedLabelStyle: TextStyle(fontSize: 16.0),
      tabs: [
        Tab(child: Text('我的',style: TextStyle(fontSize: tabIndex == 0 ? 20:16),)),  // 如果当前索引等于0字体大小就是20
        Tab(child: Text('我的',style: TextStyle(fontSize: tabIndex == 1 ? 20:16),)),
        Tab(child: Text('我的',style: TextStyle(fontSize: tabIndex == 2 ? 20:16),)),
        Tab(child: Text('我的',style: TextStyle(fontSize: tabIndex == 3 ? 20:16),)),
        Tab(child: Text('我的',style: TextStyle(fontSize: tabIndex == 4 ? 20:16),)),
        Tab(child: Text('我的',style: TextStyle(fontSize: tabIndex == 5 ? 20:16),)),
      ],
    );
  }
}

就这么简单!

相关文章

网友评论

      本文标题:Flutter TabBar 文字抖动问题最简单的解决方案

      本文链接:https://www.haomeiwen.com/subject/ysgjqctx.html