0
点赞
收藏
分享

微信扫一扫

Flutter自定义tabbar任意样式

素的盐 2024-02-21 阅读 13

场景描述

最近在使用遇到几组需要自定义的tabbar或者类似组件,在百度查询资料中通常,需要自定义

TabIndicator extends Decoration

比如上图中的带圆角的指示器这样实现

就很麻烦, 搜出来的相关也是在此之处上自己画,主要再遇到一个稍微特殊的,比如带背景切换的,带特殊图形或者path的,费事费力。

有经验同学可能就会相当那我干脆直接用radiogroup做单选然后去关联page切换。但再劳神之前,

不如点进去tabbar看一下,flutter精髓之一就是万物皆为widget,局部子的自定义正式优势所在, 

 思路描述

  /// The length of this list must match the [controller]'s [TabController.length]
/// and the length of the [TabBarView.children] list.
final List<Widget> tabs;

很明显这个是可以随意自定义的,

我们先定义好 两种切换状态的Widget

getAllTabs() {
return <Tab>[
for (int i = 0; i < controller.tabs.length; i++)
Tab(
child: Stack(
children: [
ImageUtils.assetImage(
isSelect
? "bg_data_tab_select"
: "bg_data_tab_unselect",
width: 72.w,
height: 34.w,
fit: BoxFit.cover),
// 这个是我自定义背景 文字widget 你可以使用普通text
UIText(
widgetWidth: 72.w,
widgetHeight: 34.w,
fontWeight: FontWeight.w500,
text: controller.tabs[i],
fontSize: 18.w,
textAlign: TextAlign.center,
widgetAlignment: Alignment.center,
fontColor: isSelect
? const Color(0xFF202437)
: Colors.white,
letterSpacing: -0.04,
)
],
),
),
];

此时我们只需要得到isSelect值,改变的时候动态去刷新state即可 将前面的isSelect 改为controller.tabIndex =i即可

  TabBar(
onTap: (index) {
// 赋值
controller.tabIndex = index;
// 封装的刷新 一般对应setState
controller.update();
},
举报

相关推荐

0 条评论