首页 > 解决方案 > Flutter:如何最小化 DropdownButton 的宽度

问题描述

Flutter 中的DropdownButton宽度根据DropdownMenuItem它拥有的项目中的最大值设置它的宽度。如果选择了一个小项目,则会在项目和箭头之间留下很多空白。如何使按钮缩放以适合所选项目的宽度?

我尝试使用Expanded,一些Flexible东西,但我仍然无法改变它的宽度。

DropdownButton(
    value: null,
    hint: Text("Small text"),
    items: ..., //Text widgets that have more text and are larger than the hint
)

我试图摆脱hint箭头和箭头之间下划线的空格: 在此处输入图像描述

标签: flutterflutter-layout

解决方案


用下拉按钮包裹ButtonTheme并添加alignedDropdown = true如下:

ButtonTheme(
  alignedDropdown: true,
  child: DropdownButton(...),
)

alignedDropdown 将菜单项的宽度与按钮相匹配。然后我们需要特定的宽度,所以用 SizedBox 或 Container 包裹 ButtonTheme:

SizedBox(
  width: 25, // Your width for dropdowns
  child: ButtonTheme(...),
)

推荐阅读