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

Flutter如何限制下拉菜单选项数量并实现滚动效果

解决DropdownButton下拉列表过长的问题

要限制DropdownButton下拉菜单的显示行数,让超出部分可滚动,只需给DropdownButton添加menuMaxHeight属性,设置合适的最大高度即可。

Material Design中单个DropdownMenuItem的默认高度约为48px,若想显示5个选项,设置menuMaxHeight: 48 * 5(即240);显示6个则设为48 * 6(即288),超出的选项会自动出现滚动条。

修改后的完整代码如下:

Widget build(BuildContext context) {
  return Container(
    decoration: widget.boxDecor,
    padding: widget.padding,
    margin: widget.margin,
    width: widget.width,
    height: widget.height,
    child: Center(
      child: DropdownButton<String>(
        value: widget.initialValue ?? dropdownValue,
        icon: widget.iconDropdown,
        isExpanded: true,
        elevation: 16,
        // 添加menuMaxHeight属性,限制下拉菜单高度
        menuMaxHeight: 48 * 5, // 显示5个选项的高度,可根据需求调整
        style: primaryColor400Style.copyWith(
          fontSize: fontSize10,
        ),
        underline: Container(
          height: 2,
          decoration: BoxDecoration(
            color: Colors.transparent,
          ),
        ),
        onChanged: (String? newValue) {
          if (newValue != 'Personal') {
            Provider.of<SelectedTeamProvider>(context, listen: false)
                .setSelectedTeamNameForTicket(newValue!);
          } else {
            Provider.of<SelectedTeamProvider>(context, listen: false)
                .setSelectedTeamNameForTicket('');
          }
          if (widget.onChanged != null) {
            widget.onChanged!(newValue!);
          }
          setState(() {
            dropdownValue = newValue!;
          });
        },
        items: itemLists.map<DropdownMenuItem<String>>((String value) {
          return DropdownMenuItem<String>(
            value: value,
            child: Text(value.tr()),
          );
        }).toList(),
      ),
    ),
  );
}

如果你的DropdownMenuItem使用了自定义高度,可根据实际高度调整menuMaxHeight的数值,比如自定义高度为50px,5个选项就设置为50 * 5。

内容的提问来源于stack exchange,提问作者Kim San

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 12:45:47