Flutter存储API返回data列表时遇类型不匹配错误求助
解决Flutter API数据解析错误:
String is not a subtype of type bool 错误原因
你误用了UserPostModel解析API响应中data数组的单个元素。UserPostModel是对应整个API响应的模型,其中的status字段定义为布尔类型;但data数组里的每个帖子对象的status是字符串(如"Ongoing"、"Past"),类型不匹配导致转换失败。
修正方案
方案1:仅获取data列表(帖子数据)
修改API请求方法,用Data模型解析data数组的每个元素,同时避免使用全局列表防止重复添加数据:
Future<List<Data>> getUserPost() async { var url = "APIgetUserPost.php?page=$currentPage"; var response = await http.get(Uri.parse(url)); if (response.statusCode == 200) { Map<String, dynamic> data = jsonDecode(response.body); List<dynamic> dataList = data["data"]; List<Data> posts = []; for (var item in dataList) { posts.add(Data.fromJson(item)); } print(posts); return posts; } else { print("请求失败"); return []; } }
方案2:解析完整API响应(包含分页等信息)
如果需要获取响应中的分页数据(如totalPages、hasNextPage),先把整个响应解析为UserPostModel,再从中提取data列表:
Future<UserPostModel> getFullResponse() async { var url = "APIgetUserPost.php?page=$currentPage"; var response = await http.get(Uri.parse(url)); if (response.statusCode == 200) { UserPostModel fullResponse = UserPostModel.fromJson(jsonDecode(response.body)); List<Data>? posts = fullResponse.data; print(posts); return fullResponse; } else { print("请求失败"); throw Exception("请求失败"); } }
关键说明
原代码错误的核心是:将data数组中的单个帖子对象传入UserPostModel.fromJson,而该模型会尝试把帖子里的status字符串赋值给自己的布尔类型_status字段,触发类型不匹配错误。正确的做法是用Data模型解析帖子对象,UserPostModel仅用于解析整个API响应结构。
内容的提问来源于stack exchange,提问作者Taki Rajani
相关产品推荐
相关产品推荐

