如何让Flutter中DropdownButton的菜单宽度适配文本内容?
问题原因
Flutter原生DropdownButton默认会计算所有下拉选项的最大宽度作为选中项的容器宽度,同时文本和下拉箭头之间存在默认间距,才会出现宽度不跟随当前选中文本自适应、箭头和文本间隙过大的问题。
解决步骤
给DropdownButton添加以下参数调整,同时优化选中项容器的约束:
- 新增
isDense: true,压缩组件默认的冗余内边距 - 显式设置
isExpanded: false,禁止组件自动撑满父容器宽度 - 调整
selectedItemBuilder返回的组件对齐方式,去掉无意义的外层冗余容器约束 - 可通过
padding: EdgeInsets.zero进一步去除默认内边距,压缩文本和箭头的间隙
修改后完整代码
Widget dropdownList(){ return DropdownButton<Location>( value: _selectedValue, icon: const Icon(Icons.expand_more), iconSize: 30, underline: const SizedBox(), // 核心适配参数 isDense: true, isExpanded: false, padding: EdgeInsets.zero, onChanged: (Location? newValue) { setState(() { _selectedValue = newValue!; }); }, style: const TextStyle(color: Colors.blue), selectedItemBuilder: (BuildContext context) { return locationList.map((Location value) { return Align( alignment: Alignment.centerLeft, child: Text( value.name, style: const TextStyle( color: Colors.black, fontSize: 30, fontWeight: FontWeight.w300 ), ), ); }).toList(); }, items: locationList.map<DropdownMenuItem<Location>>((Location value) { return DropdownMenuItem<Location>( value: value, child: Text( value.name, style: const TextStyle( color: Colors.black, fontSize: 15, fontWeight: FontWeight.w300 ) ), ); }).toList(), ); }
内容的提问来源于stack exchange,提问作者Huiting
相关产品推荐
相关产品推荐

