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

如何从Model列表生成DropdownButtonFormField?遇类型转换错误求助

解决TypeError (type 'List<dynamic>' is not a subtype of type 'List<DropdownMenuItem<int>>?')错误

错误根源

  1. FutureBuilder未指定泛型,导致snapshot.data被推断为dynamic,调用map生成的列表默认是List<dynamic>,无法匹配DropdownButtonFormField要求的List<DropdownMenuItem<int>>类型。
  2. DropdownButtonFormField未明确泛型参数,Dart无法精准推断items的类型约束。

修复方案

1. 给FutureBuilder指定泛型

将FutureBuilder改为FutureBuilder<List<Model>>,让snapshot.data被明确识别为List<Model>,从根源避免动态类型问题。

2. 给DropdownButtonFormField指定泛型

由于你的DropdownMenuItem的value是int类型(对应model.id),将DropdownButtonFormField改为DropdownButtonFormField<int>,明确其泛型参数为int。

3. 完善空数据校验

新增空数据判断逻辑,避免当接口返回空列表时触发空指针异常。

修复后的完整代码

Widget getDropDownMenu() {
  return FutureBuilder<List<Model>>(
    future: getOptionList(),
    builder: (BuildContext context, AsyncSnapshot<List<Model>> snapshot) {
      if (snapshot.connectionState == ConnectionState.waiting) {
        return Center(
          child: CircularProgressIndicator(),
        );
      } else if (snapshot.hasError) {
        return Center(
          child: Text('Error: ${snapshot.error}'),
        );
      } else if (!snapshot.hasData || snapshot.data!.isEmpty) {
        return Center(child: Text('No options available'));
      } else {
        return DropdownButtonFormField<int>(
          validator: (value) {
            if (value == 0) {
              return 'Please choose an option from the list';
            }
            return null;
          },
          decoration: InputDecoration(
            border: OutlineInputBorder(borderRadius: BorderRadius.circular(10)),
          ),
          value: _indicators_field_value,
          items: snapshot.data!.map((model) {
            return DropdownMenuItem<int>(
              child: Text(model.name),
              value: model.id,
            );
          }).toList(),
          onChanged: (v) {
            _indicators_field_value = v!;
          },
        );
      }
    },
  );
}

额外提醒

  • 确认Model类中的id字段是int类型,如果是其他数字类型(如String),需同步修改DropdownButtonFormField的泛型参数和DropdownMenuItem的value类型。

内容的提问来源于stack exchange,提问作者mana

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 21:05:07