You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 14:43:16