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

Flutter比特币行情应用开发遇Dart空安全与Dropdown类型报错

报错诱因分析
  • 第一个报错The body might complete normally, causing 'null' to be returned...的诱因:
    你定义的getDropDownItems方法声明返回值为List<DropdownMenuItem>,但方法体内既没有把循环生成的DropdownMenuItem添加到列表中,也没有写return语句返回列表,方法执行完成后默认返回null,和非空的返回类型声明冲突。
  • 第二个报错The argument type 'List<DropdownMenuItem>' can't be assigned to the parameter type 'List<DropdownMenuItem>?'.的诱因:
    存在两处类型不匹配问题,一是方法声明返回的是无泛型的List<DropdownMenuItem>,但DropdownButton<String>的items参数要求的是带String泛型的List<DropdownMenuItem<String>>?类型;二是第一个问题导致方法实际返回null,也触发了类型不兼容校验。
修复方案

只需要修改getDropDownItems方法即可同时解决两个报错,修改点如下:

  1. 给方法返回值加上String泛型,匹配DropdownButton的参数要求
  2. 循环内把生成的DropdownMenuItem添加到列表中
  3. 方法末尾显式返回构造好的列表

修复后的代码:

// 完整的修复后方法
List<DropdownMenuItem<String>> getDropDownItems() {
  List<DropdownMenuItem<String>> dropdownItem = [];
  for (String currency in currenciesList) {
    dropdownItem.add(DropdownMenuItem(
      child: Text(currency),
      value: currency,
    ));
  }
  return dropdownItem;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 12:54:05