Flutter单个JSON解析与ListView展示:解决类型赋值错误
解决Flutter中单个JSON对象解析及ListView展示问题
遇到的错误
A value of type 'UserModel' can't be assigned to a variable of type 'List<UserModel>'.
背景说明
使用Postman生成API请求代码,通过quicktype生成UserModel类。此前教程均针对JSON数组解析,但当前API返回的是包含数组的单个JSON对象,需调整解析逻辑并在ListView.builder中展示数据。可通过https://reqres.in/api/users?page=1复现场景。
原解析JSON数组的代码片段:
if (response.statusCode == 200) { String tempStoreDataFromApi = await response.stream.bytesToString(); List<DataModel> dataList_1 = dataModelFromJson(tempStoreDataFromApi); }
示例截图



解决方案
1. 生成正确的模型类
当前API返回的是包含data数组的根对象,而非直接返回数组。将API返回的完整JSON(调用https://reqres.in/api/users?page=1获取结果)粘贴到quicktype,生成包含根模型和UserModel的类,结构大致如下:
class ReqresResponse { int page; int perPage; int total; int totalPages; List<UserModel> data; ReqresResponse({ required this.page, required this.perPage, required this.total, required this.totalPages, required this.data, }); factory ReqresResponse.fromJson(Map<String, dynamic> json) => ReqresResponse( page: json["page"], perPage: json["per_page"], total: json["total"], totalPages: json["total_pages"], data: List<UserModel>.from(json["data"].map((x) => UserModel.fromJson(x))), ); } class UserModel { int id; String email; String firstName; String lastName; String avatar; UserModel({ required this.id, required this.email, required this.firstName, required this.lastName, required this.avatar, }); factory UserModel.fromJson(Map<String, dynamic> json) => UserModel( id: json["id"], email: json["email"], firstName: json["first_name"], lastName: json["last_name"], avatar: json["avatar"], ); }
2. 修改解析代码
先解析为根对象,再从中取出内部的data数组:
import 'dart:convert'; // ... if (response.statusCode == 200) { String tempStoreDataFromApi = await response.stream.bytesToString(); // 解析成根响应对象 ReqresResponse responseModel = ReqresResponse.fromJson(jsonDecode(tempStoreDataFromApi)); // 提取用户列表 List<UserModel> dataList_1 = responseModel.data; }
3. 使用ListView.builder展示数据
拿到用户列表后,直接传入ListView.builder构建列表:
ListView.builder( itemCount: dataList_1.length, itemBuilder: (BuildContext context, int index) { UserModel user = dataList_1[index]; return ListTile( leading: Image.network(user.avatar), title: Text('${user.firstName} ${user.lastName}'), subtitle: Text(user.email), ); }, )
内容的提问来源于stack exchange,提问作者Saad Mansoor
相关产品推荐
相关产品推荐

