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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 03:05:24