You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Flutter中创建带中间圆角的自定义TabBar?

实现带中间圆角的Flutter TabBar效果

针对你当前的代码,要实现中间带圆角的TabBar,需要调整Tab的背景装饰以及选中状态的逻辑,以下是具体修改方案:

1. 同步TabController与选中状态

首先确保_tabController和_selectedIndex保持同步,避免状态不一致:

@override
void initState() {
  super.initState();
  _tabController = TabController(length: 2, vsync: this);
  // 添加监听同步选中索引
  _tabController.addListener(() {
    if (_tabController.indexIsChanging) {
      setState(() {
        _selectedIndex = _tabController.index;
      });
    }
  });
}

@override
void dispose() {
  _tabController.dispose();
  super.dispose();
}

2. 重构_buildTab组件

修改_buildTab,为不同位置的Tab设置针对性的圆角(第一个Tab仅右上圆角,第二个仅左上圆角),并根据选中状态切换背景色:

Widget _buildTab({required String text, required bool isSelected, required bool isFirstTab}) {
  return Container(
    alignment: Alignment.center,
    width: double.infinity,
    decoration: BoxDecoration(
      color: isSelected ? Colors.green[100] : Colors.transparent, // 选中时的背景色
      borderRadius: BorderRadius.only(
        topLeft: isFirstTab ? const Radius.circular(25) : Radius.zero,
        topRight: isFirstTab ? Radius.zero : const Radius.circular(25),
      ),
    ),
    child: Text(
      text,
      style: TextStyle(
        fontSize: 18,
        color: isSelected ? Colors.black : Colors.grey, // 修正文本颜色逻辑
        fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
      ),
    ),
  );
}

3. 调整TabBar配置

去掉原有的indicator(因为选中状态由Tab背景体现),并传递isFirstTab参数给_buildTab:

TabBar(
  controller: _tabController,
  isScrollable: false,
  dividerColor: Colors.transparent,
  indicatorSize: TabBarIndicatorSize.tab,
  labelColor: Colors.transparent, // 隐藏默认文本颜色,用自定义文本样式
  unselectedLabelColor: Colors.transparent,
  tabs: [
    Tab(child: _buildTab(text: 'Phone', isSelected: _selectedIndex == 0, isFirstTab: true)),
    Tab(child: _buildTab(text: 'Email', isSelected: _selectedIndex == 1, isFirstTab: false)),
  ],
)

额外优化(可选)

如果需要给整个TabBar区域添加外边框,可以在外层套一个Container:

Container(
  decoration: BoxDecoration(
    border: Border.all(color: Colors.grey.shade300),
    borderRadius: const BorderRadius.only(
      topLeft: Radius.circular(25),
      topRight: Radius.circular(25),
    ),
  ),
  child: TabBar(
    // 上述TabBar代码
  ),
)

这样修改后,选中的Tab会显示背景色,且两个Tab中间形成圆角分割的效果,完全符合你要的带中间圆角的TabBar样式。

内容的提问来源于stack exchange,提问作者Hary Nugraha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 06:00:00