如何在保持DropdownButton isExpanded=true时缩小下拉菜单宽度?
需求:保持DropdownButton的isExpanded属性为true(按钮铺满父容器宽度),同时让弹出的下拉菜单宽度缩小,消除菜单内的空白区域,不使用第三方包。
解决方案
DropdownButton的下拉菜单默认会继承按钮的宽度,当isExpanded: true时菜单会和按钮同宽。要实现需求,只需给每个DropdownMenuItem的子组件添加宽度约束,让菜单根据内部内容自适应宽度即可,按钮仍会保持铺满父容器的状态。
方法1:固定菜单内容宽度
给DropdownMenuItem的child包裹Container,设置合适的固定宽度:
return Container( child: DropdownButton<String>( isExpanded: true, value: selectedname, items: listOfDropdownMenuItems.map((name) { return DropdownMenuItem<String>( value: name, child: Container( width: 200, // 根据实际需求调整宽度值 child: Text(name), ), ); }).toList(), onChanged: (newValue) { setname(newValue!); }, underline: Container(), ), );
方法2:自适应内容宽度
如果希望菜单宽度跟随文本内容自动调整,使用IntrinsicWidth包裹文本:
return Container( child: DropdownButton<String>( isExpanded: true, value: selectedname, items: listOfDropdownMenuItems.map((name) { return DropdownMenuItem<String>( value: name, child: IntrinsicWidth( child: Text(name), ), ); }).toList(), onChanged: (newValue) { setname(newValue!); }, underline: Container(), ), );
说明
- 两种方法都能让下拉菜单脱离按钮宽度的限制,根据内部内容调整宽度,消除空白区域。
- 按钮因为
isExpanded: true的设置,依然会铺满父容器宽度。
内容的提问来源于stack exchange,提问作者Ahsan
相关产品推荐
相关产品推荐

