Flutter如何限制下拉菜单选项数量并实现滚动效果
要限制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
相关产品推荐
相关产品推荐

