Flutter出现_TypeError:Map无法转为List<CustomerList>,需实现数据上传与消息展示
解决Flutter中的_TypeError: '_Map<String, dynamic>' is not a subtype of type 'List'错误
错误原因
- 你在请求处理代码中,错误地将接口响应
data数组的第一个元素(单个Map对象)传给了CustomerResponse.fromJson,但该构造函数期望接收包含message、status、code、data字段的完整响应JSON对象,而非单个客户数据。 - 错误分支里的
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
相关产品推荐
相关产品推荐

