Flutter中如何解决「期望类型'List<DropdownMenuItem<Object>>?',实际为'List<dynamic>'」错误?
解决自定义Dropdown组件传入记录列表的错误
首先,你的代码存在几个关键问题,直接导致组件运行出错,以下是针对性修复方案及说明:
1. 明确泛型类型
DropdownButton需要指定泛型,由于你的value是int类型(对应item.id),必须声明为DropdownButton<int>,避免类型推断混乱引发错误。
2. 规范参数类型
自定义函数的参数必须明确类型,消除动态类型带来的潜在问题:
dataList:指定为对应记录类的列表(比如你的记录类是Record,就写List<Record>)val:指定为int?(支持初始值为null的场景)ReturnSelectedValue:指定为Function(int?)
3. 修复后的完整代码
假设你的记录类定义如下:
class Record { final int id; final String? name; Record({required this.id, this.name}); }
修改后的Dropdown组件代码:
Widget DropDownList(List<Record> dataList, int? val, Function(int?) ReturnSelectedValue) { return DropdownButton<int>( value: val, isExpanded: true, items: dataList.map((item) { return DropdownMenuItem<int>( value: item.id, child: Text(item.name ?? '默认名称'), ); }).toList(), onChanged: (selectedvalue) { ReturnSelectedValue(selectedvalue); }, ); }
关键修复点说明
- 给
DropdownButton和DropdownMenuItem添加<int>泛型,确保值的类型与item.id完全匹配 - 为所有参数明确类型,避免动态类型导致的类型不匹配错误
- 将
item.name!替换为item.name ?? '默认名称',防止name为null时触发空指针异常 - 确保传入的
val必须是dataList中某个item的id,或者为null,否则会抛出“value not in items”错误
内容的提问来源于stack exchange,提问作者Tony Lam
相关产品推荐
相关产品推荐

