如何在DropdownButton中隐藏选中DropdownItem的文本,仅显示图标?
问题描述


我创建了一个包含两个DropdownItem(share和edit)的DropdownButton。每当选中一个DropdownItem(例如图2中的edit),选中项的文本就会显示出来(如图2所示)。我不希望出现这种情况,即使选中DropdownItem,我也只想显示图标(此处为信息图标)。
我尝试过设置isDense为true,或者用SizedBox包裹DropdownButton并设置width,但都没有效果。
解决方案
你可以通过DropdownButton的selectedItemBuilder参数自定义选中状态下的显示内容,强制让它始终展示指定图标,而非选中项的文本。
示例代码如下:
String? selectedOption; final List<String> options = ['share', 'edit']; // 在build方法中使用 DropdownButton<String>( value: selectedOption, selectedItemBuilder: (BuildContext context) { // 无论选中哪个选项,都返回目标图标 return options.map((String item) { return const Icon(Icons.info); // 替换为你的信息图标 }).toList(); }, items: options.map((String option) { return DropdownMenuItem<String>( value: option, child: Text(option), ); }).toList(), onChanged: (String? newValue) { setState(() { selectedOption = newValue; }); }, // 把默认图标也设为相同样式,保证展开前后显示统一 icon: const Icon(Icons.info), underline: const SizedBox(), // 不需要下划线可保留此设置 )
selectedItemBuilder会覆盖选中状态的默认显示逻辑,不管当前选中哪项,都会渲染你定义的图标。同时将icon参数设置为相同图标,能让按钮在收起状态的显示保持一致。
内容的提问来源于stack exchange,提问作者Smashell
相关产品推荐
相关产品推荐

