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

Flutter TabBar激活态标签间距适配问题求助

Flutter TabBar激活态标签间距异常修复方案

问题原因

你给每个Tab外层硬设了MediaQuery.of(context).size.width / 2的宽度,但TabBar本身带有默认内边距,且外层容器宽度设为全屏,和父容器的width: MediaQuery.of(context).size.width / 1.09冲突,导致激活态的蓝色背景(indicator)和标签文本的间距出现异常。

修复后代码

Widget build(BuildContext context) {
  return Container(
    width: MediaQuery.of(context).size.width / 1.09,
    padding: const EdgeInsets.only(top: 14.0),
    decoration: BoxDecoration(
      color: Colors.white,
      borderRadius: BorderRadius.circular(20.0),
    ),
    child: Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        Container(
          height: 45,
          width: double.infinity,
          decoration: BoxDecoration(
            color: Colors.grey[300],
            borderRadius: BorderRadius.circular(25.0),
          ),
          child: TabBar(
            controller: _tabController,
            // 消除TabBar默认内边距,让背景与标签对齐
            labelPadding: EdgeInsets.zero,
            indicator: BoxDecoration(
              borderRadius: BorderRadius.circular(25.0),
              color: const Color(0xFF1480E0),
            ),
            labelColor: Colors.white,
            unselectedLabelColor: Colors.black,
            // 移除Tab外层自定义宽度容器,让TabBar自动分配空间
            tabs: const [
              Tab(text: 'tab 1'),
              Tab(text: 'tab 2'),
            ],
          ),
        ),
        Container(
          height: MediaQuery.of(context).size.height * 0.43,
          child: TabBarView(
            controller: _tabController,
            children: [
              Center(
                child: Text(
                  'Content 1',
                  style: TextStyle(
                    fontSize: 25,
                    fontWeight: FontWeight.w600,
                  ),
                ),
              ),
              Center(
                child: Text(
                  'Content 2',
                  style: TextStyle(
                    fontSize: 25,
                    fontWeight: FontWeight.w600,
                  ),
                ),
              ),
            ],
          ),
        ),
      ],
    ),
  );
}

核心修改说明

  • 移除Tab外层的自定义宽度容器:非滚动状态下,TabBar会自动平均分配Tab宽度,无需手动干预
  • 添加labelPadding: EdgeInsets.zero:清除TabBar自带的左右内边距,解决激活态背景和标签的间距错位
  • 把TabBar父容器宽度改为double.infinity:适配父容器的限定宽度,避免布局溢出

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 01:03:15