Flutter调用API填充下拉列表出现类型转换异常求解
问题解决:类型转换异常(String 无法转为 int 作为索引)
错误根源
你在getData()方法里直接将API返回的原始字符串(res.body)传给DropDownModel.fromJson(),但DropDownModel.fromJson()的参数需要是JSON解码后的Map对象,而非字符串。当传入字符串时,代码会尝试用json['status']的方式去索引字符串(相当于取字符串的第N个字符),而字符串的索引必须是整数,这就触发了type 'String' is not a subtype of type 'int' of 'index'异常。
修复步骤
1. 修正getData()的JSON解码逻辑
先将API返回的字符串解码为Map对象,再传入模型的fromJson方法:
getData() async{ var res = await http.get(Uri.parse(link)); if(res.statusCode == 200){ // 先解码JSON字符串为Map,再传入fromJson DropDownModel data = DropDownModel.fromJson(json.decode(res.body)); // 或者直接用生成的工具方法,更简洁 // DropDownModel data = dropDownModelFromJson(res.body); return data; }else{ print("Something went wrong"); return null; // 明确返回null,避免后续空值错误 } }
2. 处理customerDropDwon()的空值安全
getData()可能返回null,需先判断数据有效性,同时避免在组件销毁后调用setState:
customerDropDwon() async{ DropDownModel? data = await getData(); if(mounted && data != null && data.data != null){ setState(() { customerList = data.data!; }); } }
3. 规范DropdownButton的类型(可选)
明确DropdownButton的泛型类型,避免类型推断歧义,同时处理字段空值:
DropdownButton<String>( hint: const Text("customer"), items: customerList.map((e){ return DropdownMenuItem<String>( child: Text(e.name ?? "Unknown"), // 处理name为null的情况 value: e.id, ); }).toList(), value: selectedCustomer, onChanged: (newVal){ setState(() { selectedCustomer = newVal; }); }, )
额外建议
- 优先使用生成的
dropDownModelFromJson()工具方法,它已封装了解码逻辑,减少手动出错概率。 - 对所有可能为null的字段(如
e.name)做空值处理,避免空指针异常。
内容的提问来源于stack exchange,提问作者Taki Rajani
相关产品推荐
相关产品推荐

