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

如何在Flutter的TabBar中添加垂直分隔线?

解决TabBar添加垂直分隔线且保持标签居中的问题

要实现TabBar中两个标签间的垂直分隔线,同时保证标签文本居中,你可以通过调整Tab的内部布局来避免直接添加Container导致的偏移问题,以下是修改后的代码:

Container(
  height: 38,
  decoration: BoxDecoration(
    border: Border(
      bottom: BorderSide(color: AppColors.borderColor),
      top: BorderSide(color: AppColors.borderColor),
    ),
  ),
  padding: const EdgeInsets.symmetric(vertical: 7),
  child: TabBar(
    indicatorColor: Colors.transparent,
    labelColor: AppColors.primaryColor,
    unselectedLabelColor: Colors.black,
    dividerColor: Colors.black,
    labelPadding: EdgeInsets.zero, // 移除默认内边距,避免布局偏移
    isScrollable: false, // 确保两个Tab平分宽度,显式声明更清晰
    tabs: [
      Tab(
        child: Row(
          children: [
            Expanded(
              child: Text(
                'Products',
                textAlign: TextAlign.center,
                style: kButtonsStyle.copyWith(
                  fontWeight: FontWeight.w400,
                ),
              ),
            ),
            // 添加垂直分隔线
            Container(
              width: 1,
              height: 24, // 控制分隔线高度,匹配示例图的留白效果
              color: AppColors.borderColor,
            ),
          ],
        ),
      ),
      Tab(
        child: Text(
          'Suppliers',
          textAlign: TextAlign.center,
          style: kButtonsStyle.copyWith(
            fontWeight: FontWeight.w400,
          ),
        ),
      )
    ],
  ),
),

关键调整说明:

  • 移除默认内边距:设置labelPadding: EdgeInsets.zero,消除TabBar默认的左右内边距,避免分隔线位置偏移。
  • Tab内部布局优化:第一个Tab用Row包裹Expanded文本和分隔线,Expanded让文本占据Tab全部可用宽度,配合textAlign: TextAlign.center保证文本居中,分隔线固定在Tab右侧,刚好处于两个Tab的中间位置。
  • 控制分隔线高度:将分隔线高度设为24,与示例图中上下留白的视觉效果一致,更协调美观。

你也可以选择给第二个Tab左侧添加分隔线,达到同样的中间分隔效果,根据个人偏好调整即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 17:32:34