Flutter调用API报错:_Map<String,dynamic>非String子类型
解决Flutter API调用中的
type '_Map<String, dynamic>' is not a subtype of type 'String'错误 这个错误的核心是代码中将Map类型的数据当作String类型使用,大概率出现在JSON解析阶段,或API响应处理时的类型不匹配。结合你提供的API返回、数据模型和调用函数,按以下步骤排查:
1. 核对API返回与模型字段的类型匹配
逐行对比API返回的每个字段类型和你的数据模型定义:
- 比如API返回里某字段是嵌套Map:
如果你的模型里把{ "profile": {"id": 123, "username": "Ayush"}, "status": "ok" }profile定义为String profile;,就会触发错误——正确做法是为profile定义对应的子模型(比如ProfileModel),并将字段类型设为ProfileModel profile;。
2. 检查JSON反序列化逻辑
- 手动解析JSON时,避免直接将Map赋值给String字段:
错误示例:
修正后:class UserModel { String profile; String status; UserModel.fromJson(Map<String, dynamic> json) { profile = json['profile']; // json['profile']是Map,却赋值给String类型字段 status = json['status']; } }class UserModel { ProfileModel profile; String status; UserModel.fromJson(Map<String, dynamic> json) { profile = ProfileModel.fromJson(json['profile']); status = json['status']; } } class ProfileModel { int id; String username; ProfileModel.fromJson(Map<String, dynamic> json) { id = json['id']; username = json['username']; } } - 若使用
json_serializable代码生成,确保每个字段的类型注解正确,无错误的@JsonKey配置。
3. 排查API响应的处理流程
确认没有把整个响应体(Map)直接当作String使用:
错误示例:
final response = await http.get(Uri.parse(apiUrl)); String responseData = json.decode(response.body); // json.decode返回Map<String, dynamic>,不能赋值给String
正确处理:
final response = await http.get(Uri.parse(apiUrl)); Map<String, dynamic> responseData = json.decode(response.body); final userModel = UserModel.fromJson(responseData);
4. 调试定位具体出错字段
通过打印或调试工具快速定位问题:
- 加打印语句输出变量类型:
print(json['profile'].runtimeType); // 输出Map<String, dynamic>或String,直接定位不匹配的字段 - 使用Flutter DevTools查看变量的实际类型和值,对比模型定义。
内容的提问来源于stack exchange,提问作者Ayush Ranjan Rout
相关产品推荐
相关产品推荐

