Flutter 横向列表中如何让三个 ElevatedButton 等宽并固定尺寸?
数据小陈
结论
ElevatedButton 高度被撑满,主要原因是水平 ListView 在交叉轴(垂直方向)给 item 施加了紧约束。把 SizedBox 套在 item 里绕不开这个约束,fixedSize 遇到紧约束也会失效。按钮固定为三个时,优先用 Row + Expanded + AspectRatio;如果一定要用横向 ListView,就要给 ListView 明确高度,同时让 item 有固定宽高。
原因
- 水平
ListView的主轴是水平方向,交叉轴是垂直方向。viewport 会把交叉轴尺寸传给 item,item 的高度就容易被撑满。 shrinkWrap: true只影响主轴方向是否包裹内容,不改变交叉轴约束。ElevatedButton.styleFrom的fixedSize、minimumSize、maximumSize并不能保证最终尺寸,父级紧约束会优先起作用。- 原代码里,外层
SizedBox的高度是屏幕宽 / 4,ListView也占了这个高度,按钮自然跟着占满。
方案一:固定三个按钮,用 Row 等宽布局
在 _ButtonsStatefulWidgetState.build 中把原来的 SizedBox + Row + ListView 换成类似下面的写法:
SizedBox(
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.width / 3,
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: List.generate(3, (index) {
return Expanded(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 8),
child: AspectRatio(
aspectRatio: 1,
child: ElevatedButton(
style: (index == _selected ? styleSelected : styleDefault).copyWith(
shape: const CircleBorder(),
padding: EdgeInsets.zero,
),
onPressed: () {
setState(() {
_selected = index;
});
},
child: Text(index.toString()),
),
),
),
);
}),
),
)
Expanded 让三个按钮等宽,AspectRatio 让宽高相等,CircleBorder 把按钮变成圆形。父级高度要留够,否则 AspectRatio 会按高度反推宽度,可能挤小按钮。
方案二:必须用横向 ListView
如果按钮数量不固定、需要横向滚动,可以保留 ListView,但要显式控制交叉轴高度:
SizedBox(
width: MediaQuery.of(context).size.width,
height: 80,
child: ListView.separated(
scrollDirection: Axis.horizontal,
itemCount: 3,
separatorBuilder: (_, __) => const SizedBox(width: 16),
itemBuilder: (context, index) {
return SizedBox(
width: 80,
height: 80,
child: ElevatedButton(
style: (index == _selected ? styleSelected : styleDefault).copyWith(
shape: const CircleBorder(),
padding: EdgeInsets.zero,
),
onPressed: () {
setState(() {
_selected = index;
});
},
child: Text(index.toString()),
),
);
},
),
)
这里 ListView 的高度和 item 的 SizedBox 高度一致,按钮就不会被额外拉伸。如果想让 ListView 占满可用宽度,别只靠 shrinkWrap;把它放进有界宽度的容器,或者用 Expanded。
注意事项
- 圆形按钮要同时设置
shape: CircleBorder()、padding: EdgeInsets.zero,并保证宽高一致。 - 按钮文字较大时,圆形按钮容易溢出,可调小
fontSize或使用FittedBox。 - 按钮固定为三个时,直接用
Row更简单;数量会变、还可能滚动时,再用ListView或SingleChildScrollView。
备注:内容仅供参考。
