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

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

消除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,加上组件本身的最小尺寸限制,导致即使没有显示内容也占据了空间。按以下步骤修改:

  1. 隐藏第二个DropdownButton的下拉图标:给第二个组件添加iconSize: 0.0,和第一个保持一致,消除图标占位的宽度。
  2. 移除内部默认padding:给两个DropdownButton都设置padding: EdgeInsets.zero,去掉组件自带的内边距。
  3. 压缩组件最小尺寸(可选):如果第二个组件在无内容时需要更紧凑,添加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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 00:15:28