阅读 256

flutter自定义tabbar

自定义tabbar主要是修改滑动条的样式,字体和颜色根据需求自己改

原始的tabbar样式

tabbar_0.gif

样式一

tabbar_2.gif

这个不需要修改原始的Tabbar代码,只需要修改indicator的样式

TabBar(
  tabs: tabList,
  indicatorColor: Colors.white,
  indicatorWeight: 0,
  indicator: BoxDecoration(
      color: Colors.white,
      borderRadius: BorderRadius.circular(45.sp),
      border: Border.all(width: 10.sp,color: GsColors.gray10)
  ),
  labelColor: GsColors.blue,
  unselectedLabelColor: GsColors.black,
  labelStyle: TextStyle(
    color: Colors.blue,
    fontWeight: FontWeight.bold,
    fontSize: GsFontSize.sp_36,
  ),
  unselectedLabelStyle: TextStyle(
    fontSize: GsFontSize.sp_36,
    // fontWeight: FontWeight.bold,
  ),
)复制代码

样式二

tabbar_1.gif

由于这个indicator的长和宽都是固定的,通过上面的方式无法修改,这时候需要深入Tabbar的源码去自定义效果。 下面是使用自定义类名后的tabbar,将Tabar类名改成CustomTabBarWidget,文件中相关的都要改类名

Container(
  width: ScreenUtil().screenWidth,
  color: bgColor ?? Colors.white,
  alignment: Alignment.centerLeft,
  child: SingleChildScrollView(
    scrollDirection: Axis.horizontal,
    child: CustomTabBarWidget(
      height: height ?? 130.sp,
      isScrollable: true,
      labelColor: selectLabelColor ?? GsColors.black,
      unselectedLabelColor: unselectLabelColor ?? Color(0xff666666),
      labelStyle: TextStyle(fontSize: 46.sp, fontWeight: GsFontWeight.medium),
      unselectedLabelStyle: TextStyle(fontSize: 44.sp, fontWeight: GsFontWeight.regular),
      indicatorWeight: 12.sp,
      indicatorColor: indicatorColor ?? GsColors.blueMain,
      indicatorSize: TabBarIndicatorSize.label,
      tabs: tabList,
    ),
  ),
)复制代码

将flutter的Tabbar拷贝一份,然后修改Tabbar类名,找到indicator的paint方法,在里面修改indicator的size。原代码中的indicator的size是根据tabbar的item的size去改变的

原代码:

if (indicatorSize == TabBarIndicatorSize.label) {
  final double tabWidth = tabKeys[tabIndex].currentContext!.size!.width;
  final double delta = ((tabRight - tabLeft) - tabWidth) / 2.0;
  tabLeft += delta;
  tabRight -= delta;
}

final EdgeInsets insets = indicatorPadding.resolve(_currentTextDirection);
final Rect rect = Rect.fromLTWH(tabLeft, 0.0, tabRight - tabLeft, tabBarSize.height);复制代码

修改后代码:

///滑动条的宽和高
double indicatorWidth = 58.sp;
double indicatorHeight = 12.sp;

if (indicatorSize == TabBarIndicatorSize.label) {
  final double tabWidth = tabKeys[tabIndex].currentContext.size.width;
  final double delta = ((tabRight - tabLeft - indicatorWidth)) / 2.0;
  tabLeft += delta;
  tabRight -= delta;
}
final EdgeInsets insets = indicatorPadding.resolve(_currentTextDirection);
final Rect rect = Rect.fromLTWH(tabLeft, tabBarSize.height - indicatorHeight, indicatorWidth, indicatorHeight);


作者:justyouzxy
链接:https://juejin.cn/post/7017719421749690381


文章分类
后端
文章标签
版权声明:本站是系统测试站点,无实际运营。本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 XXXXXXo@163.com 举报,一经查实,本站将立刻删除。
相关推荐