Flutter中如何消除Row组件内两个DropdownButton之间的间距?

问题描述
我使用了一个Row组件,其包含两个DropdownButton作为子组件。我注释掉了第二个DropdownButton的value相关代码,但两者之间的间距仍然存在,请问该如何消除这个间距?
相关代码
return Center( child: Row( children: [ DropdownButton<ActivityPriority>( value: widget.selectedValue != null ? dropdownItemsLandscape[checkValueIndex()].value : null, hint: Text(S.of(context).select), items: dropdownItemsPortrait, iconSize: 0.0, underline: Container(), onChanged: (v) { setState(() { selectedValue = v; widget.onSelection(v); }); }, ), DropdownButton<ActivityPriority>( // value: widget.selectedValue != null // ? dropdownItemsLandscape[checkValueIndex()].value // : null, // hint: Text(S.of(context).select), items: dropdownItemsLandscape, underline: Container(), onChanged: (v) { setState(() { selectedValue = v; widget.onSelection(v); }); }, ), ], ), );
解决方案
间距存在的核心原因是第二个DropdownButton保留了默认的下拉图标占位和内部padding,加上组件本身的最小尺寸限制,导致即使没有显示内容也占据了空间。按以下步骤修改:
- 隐藏第二个DropdownButton的下拉图标:给第二个组件添加
iconSize: 0.0,和第一个保持一致,消除图标占位的宽度。 - 移除内部默认padding:给两个
DropdownButton都设置padding: EdgeInsets.zero,去掉组件自带的内边距。 - 压缩组件最小尺寸(可选):如果第二个组件在无内容时需要更紧凑,添加
isDense: true来进一步缩小组件的最小显示空间。
修改后的代码示例:
return Center( child: Row( children: [ DropdownButton<ActivityPriority>( value: widget.selectedValue != null ? dropdownItemsLandscape[checkValueIndex()].value : null, hint: Text(S.of(context).select), items: dropdownItemsPortrait, iconSize: 0.0, underline: Container(), padding: EdgeInsets.zero, onChanged: (v) { setState(() { selectedValue = v; widget.onSelection(v); }); }, ), DropdownButton<ActivityPriority>( // value: widget.selectedValue != null // ? dropdownItemsLandscape[checkValueIndex()].value // : null, // hint: Text(S.of(context).select), items: dropdownItemsLandscape, underline: Container(), iconSize: 0.0, padding: EdgeInsets.zero, isDense: true, onChanged: (v) { setState(() { selectedValue = v; widget.onSelection(v); }); }, ), ], ), );
另外,如果你是想在特定条件下完全隐藏第二个DropdownButton,建议用if语句或者Visibility组件控制它是否出现在Row的子组件列表中,而不是仅注释value和hint属性。
内容的提问来源于stack exchange,提问作者behnami454
相关产品推荐
相关产品推荐

