Flutter:'_InternalLinkedHashMap'不是'Iterable'子类型错误解决
解决Flutter API数据解析的两个类型不匹配错误
让我一步步帮你拆解并解决这两个问题:
第一个错误:'_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Iterable<dynamic>'
你最初的代码里,jsonDecode(response.body.toString())得到的是一个完整的Map对象(对应API响应的外层结构:包含status、result、data数组等字段),但你直接用for (var i in data)去遍历这个Map——而Map本身不是可迭代的集合,自然就抛出了这个类型不匹配的错误。你真正需要遍历的是Map里data字段对应的数组,而非整个外层Map。
第二个错误:'String' is not a subtype of type 'bool?'
你修改后的代码里,尝试把data数组里的单个帖子对象传给UserPostModel.fromJson(),但UserPostModel是用来解析整个API响应的模型:它的fromJson方法会尝试读取json['status'](外层响应里的布尔值true),但你传入的单个帖子对象里的status是字符串(比如"Ongoing"),布尔类型和字符串类型无法兼容,这就触发了第二个错误。
正确的解决方案
首先明确模型的分工:
UserPostModel对应整个API响应的完整结构(包含状态、结果、帖子数组、分页信息)Data对应每个帖子的具体数据
方案一:保留完整响应信息(适合需要分页逻辑的场景)
这种方式会解析整个API响应,同时拿到帖子列表和分页数据:
// 注意:列表类型要改为List<Data>,因为我们存储的是单个帖子数据 List<Data> myList = []; Future<List<Data>> getUserPost() async { var url = "https://your-api-domain/getUserPost.php?page=$currentPage"; var response = await http.get(Uri.parse(url)); if (response.statusCode == 200) { // 先把整个响应解析为UserPostModel对象 UserPostModel fullResponse = UserPostModel.fromJson(jsonDecode(response.body)); // 检查帖子数组是否存在,再添加到本地列表 if (fullResponse.data != null) { myList.addAll(fullResponse.data!); } // 如果需要分页,可以在这里获取totalPages、hasNextPage等字段 print("Total pages: ${fullResponse.totalPages}"); print(myList); return myList; } else { print("Failed to fetch data"); return myList; } }
方案二:直接解析帖子数组(仅需帖子数据时使用)
如果不需要外层的分页信息,可以直接提取并解析data数组:
List<Data> myList = []; Future<List<Data>> getUserPost() async { var url = "https://your-api-domain/getUserPost.php?page=$currentPage"; var response = await http.get(Uri.parse(url)); if (response.statusCode == 200) { Map<String, dynamic> responseMap = jsonDecode(response.body); List<dynamic> postsJson = responseMap['data']; // 将每个JSON对象转换为Data模型 myList = postsJson.map((postJson) => Data.fromJson(postJson)).toList(); print(myList); return myList; } else { print("Failed to fetch data"); return myList; } }
关键注意事项
- 务必保证
myList的类型是List<Data>,而不是List<UserPostModel>——UserPostModel是整个响应的容器,不是单个帖子的模型。 - 如果需要实现加载更多功能,推荐使用方案一,这样可以通过
fullResponse.hasNextPage和fullResponse.currentPage来判断是否还有下一页数据。
内容的提问来源于stack exchange,提问作者Taki Rajani
相关产品推荐
相关产品推荐

