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方法即可同时解决两个报错,修改点如下:
- 给方法返回值加上
String泛型,匹配DropdownButton的参数要求 - 循环内把生成的
DropdownMenuItem添加到列表中 - 方法末尾显式返回构造好的列表
修复后的代码:
// 完整的修复后方法 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
相关产品推荐
相关产品推荐

