如何在DropdownBelow组件中显示不在选项列表内的hintText提示文本
问题根因
DropdownBelow组件的hint仅在value为null时才会显示,你之前的操作触发了两个问题:
- 传空字符串
""作为value:空字符串不在你的categorylist选项列表里,触发了组件的断言校验报错 - 传列表中存在的
"Other"作为value:value不为null,组件直接显示选中值,覆盖hint内容
解决方法
1. 调整选中变量的默认值
将_selectedCategory的默认值改为null,注意变量类型声明为可空:
String? _selectedCategory = null;
2. 调整onChanged回调的空值兼容处理
onChanged: (newValue) { setState(() { // 兼容null的情况,只有选中有效值才赋值 if (newValue != null) { _selectedCategory = newValue as String; _newCatgoryFlag = _selectedCategory == "Other"; } }); },
如果后续需要重置回显示hint的状态,直接把_selectedCategory赋值回null即可。
修改后的完整代码示例
var categorylist = <String>[ 'Other', ]; // 改为可空类型,默认值为null String? _selectedCategory = null; Container( width: MediaQuery.of(context).size.width * 0.9, child: DropdownBelow( itemWidth: 370, itemTextstyle: TextStyle( fontSize: 14, fontWeight: FontWeight.w400, color: Colors.black), boxTextstyle: TextStyle( fontWeight: FontWeight.w400, color: Colors.black), boxPadding: EdgeInsets.fromLTRB(13, 12, 13, 12), boxWidth: 370, boxHeight: 50, boxDecoration: BoxDecoration( color: Colors.transparent, shape: BoxShape.rectangle, borderRadius: new BorderRadius.all(new Radius.circular(10.0)), border: Border.all(width: 1, color: Colors.grey)), icon: Icon( Icons.keyboard_arrow_down_outlined, color: Colors.black, ), hint: Text('Category', style: GoogleFonts.montserrat( color: HexColor("#6e6b7b"), fontSize: 15)), // 传入null的value,此时会显示hint value: _selectedCategory, items:categorylist.map<DropdownMenuItem<String>>((String value) { return DropdownMenuItem<String>( value: value, child: Text(value, style: GoogleFonts.montserrat( color: HexColor("#6e6b7b"), ))); }).toList(), onChanged: (newValue) { setState(() { if (newValue != null) { _selectedCategory = newValue.toString(); _newCatgoryFlag = _selectedCategory == "Other"; } }); }, ), ),
内容的提问来源于stack exchange,提问作者TimeToCode
相关产品推荐
相关产品推荐

