为什么我的Flutter代码中Row组件之间存在大量垂直间距?
问题原因
- 外层固定高度为100的
SizedBox远大于两个按钮行的实际总高度,Column默认会占满父容器高度,空闲空间默认会分配到子元素之间,形成多余间距 ElevatedButton默认开启了点击区域扩展属性MaterialTapTargetSize.padded,会在按钮上下额外增加点击区域高度,间接拉大了行间距Column未设置紧凑布局属性,没有主动控制子元素间距
解决方案
按以下步骤修改代码即可消除多余垂直间距:
- 给
Column添加mainAxisSize: MainAxisSize.min属性,让Column只占用实际需要的高度,不要撑满父级SizedBox - 给所有
ElevatedButton的style中添加tapTargetSize: MaterialTapTargetSize.shrinkWrap,关闭按钮默认的额外点击区域扩展 - 可以自行在两个Row之间添加指定高度的
SizedBox来控制行间距,也可以根据需求调整外层SizedBox的固定高度 - 可选:如果不需要固定外层高度,可以直接删掉外层的
SizedBox组件,让布局自适应高度
修改后的参考代码:
Positioned( bottom: 15, left: 15, child: SizedBox( // 可根据实际需求调整高度,或者直接删掉这个SizedBox自适应 height: 60, child: Column( mainAxisSize: MainAxisSize.min, children: [ Row( children: [ ElevatedButton( style: TextButton.styleFrom( padding: EdgeInsets.zero, minimumSize: Size(40, 20), backgroundColor: colorSet.buttonForeground, tapTargetSize: MaterialTapTargetSize.shrinkWrap, ), onPressed: () {}, child: Text( 'Once', style: TextStyle( color: colorSet.text, fontSize: 12, ), ), ), SizedBox(width: 8,), ElevatedButton( style: TextButton.styleFrom( padding: EdgeInsets.zero, minimumSize: Size(40, 20), backgroundColor: colorSet.buttonForeground, tapTargetSize: MaterialTapTargetSize.shrinkWrap, ), onPressed: () {}, child: Text( 'Specific Days', style: TextStyle( color: colorSet.text, fontSize: 12, ), ), ), ], ), // 手动控制两个Row的垂直间距,可自行调整数值 SizedBox(height: 8,), Row( children: [ ElevatedButton( style: TextButton.styleFrom( padding: EdgeInsets.zero, minimumSize: Size(40, 20), backgroundColor: colorSet.buttonForeground, tapTargetSize: MaterialTapTargetSize.shrinkWrap, ), onPressed: () {}, child: Text( 'Daily', style: TextStyle( color: colorSet.text, fontSize: 12, ), ), ), SizedBox(width: 3,), ElevatedButton( style: TextButton.styleFrom( padding: EdgeInsets.zero, minimumSize: Size(40, 20), backgroundColor: colorSet.buttonForeground, tapTargetSize: MaterialTapTargetSize.shrinkWrap, ), onPressed: () {}, child: Text( 'Weekly', style: TextStyle( color: colorSet.text, fontSize: 12, ), ), ), ], ), ], ), ) )
内容的提问来源于stack exchange,提问作者SoulAndBone
相关产品推荐
相关产品推荐

