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

Flutter出现_TypeError:Map无法转为List<CustomerList>,需实现数据上传与消息展示

解决Flutter中的_TypeError: '_Map<String, dynamic>' is not a subtype of type 'List'错误

错误原因

  1. 你在请求处理代码中,错误地将接口响应data数组的第一个元素(单个Map对象)传给了CustomerResponse.fromJson,但该构造函数期望接收包含message、status、code、data字段的完整响应JSON对象,而非单个客户数据。
  2. 错误分支里的CustomerResponse(custList: response.data)直接将原始字符串赋值给需要List<CustomerList>类型的custList,同样会导致类型不匹配。

修正方案

1. 修正响应解析逻辑

直接将完整的解析后JSON对象传入CustomerResponse.fromJson,而非截取data[0]。

2. 修复错误分支的类型问题

在解析失败或请求失败时,返回类型匹配的空列表,避免类型错误。

3. 实现成功消息展示

解析成功后,通过CustomerResponse的message字段获取服务器返回的提示信息,展示给用户。

修正后的请求处理代码

try { 
  response = await postMethod(uri: url, body: body, mobileNo: custMobileNo); 
} catch (e) { 
  response = null; 
} 

if (response != null && response.statusCode == 200) { 
  try { 
    final decodedJson = convert.jsonDecode(response.data);
    final customerResponse = CustomerResponse.fromJson(decodedJson);
    // 展示成功消息,示例用SnackBar
    // ScaffoldMessenger.of(context).showSnackBar(
    //   SnackBar(content: Text(customerResponse.message ?? "操作成功")),
    // );
    return customerResponse;
  } catch (e) { 
    return CustomerResponse(custList: []); 
  } 
} else { 
  return CustomerResponse(custList: []); 
}

额外注意事项

  • 确保CustomerResponse类的custList字段类型为List<CustomerList>?或List<CustomerList>,与解析逻辑匹配。
  • 服务器返回的完整响应结构应符合以下格式(与你的fromJson逻辑对应):
{
  "message": "操作成功",
  "status": "success",
  "code": 200,
  "data": [
    {"id": 1, "name": "客户A"},
    {"id": 2, "name": "客户B"}
  ]
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 05:00:27