Flutter中如何修改选中Tab高度并与未选中Tab高度统一?
解决Flutter TabBar选中与未选中Tab高度不一致的问题
要实现选中和未选中Tab高度统一,你可以通过以下调整解决:
- 给每个Tab设置
padding: EdgeInsets.zero,消除Tab自带的默认内边距,让自定义容器完全控制Tab尺寸 - 统一Tab子容器的高度(比如你设置的40),并添加内容居中对齐
- 配合indicator的参数设置,确保其高度与容器高度匹配
修改后的代码示例:
Widget tabBar() { return SingleChildScrollView( child: TabBar( isScrollable: true, padding: const EdgeInsets.symmetric(vertical: 10), unselectedLabelStyle: const TextStyle( fontSize: 14, fontWeight: FontWeight.w400, color: Color(0xFF000000), ), labelStyle: const TextStyle( fontSize: 14, fontWeight: FontWeight.w700, color: Color(0xFFffffff), ), indicatorSize: TabBarIndicatorSize.label, indicator: BoxDecoration( borderRadius: BorderRadius.circular(20), color: const Color(0xFF000000), ), tabs: [ Tab( // 移除Tab默认内边距 padding: EdgeInsets.zero, child: Container( height: 40, alignment: Alignment.center, // 确保文字居中显示 padding: const EdgeInsets.symmetric(horizontal: 20), // 按需设置左右内边距 child: const Text("标签1"), ), ), Tab( padding: EdgeInsets.zero, child: Container( height: 40, alignment: Alignment.center, padding: const EdgeInsets.symmetric(horizontal: 20), child: const Text("标签2"), ), ), // 其余Tab按同样方式配置 ], ), ); }
如果仍存在细微高度差,可额外给TabBar添加labelPadding: EdgeInsets.zero,确保indicator与容器完全贴合。这种方式无需自定义绘制,就能实现两种状态下Tab高度的统一。
内容的提问来源于stack exchange,提问作者ddongyun
相关产品推荐
相关产品推荐

