Flutter中如何通过自定义Model从Future中获取字段值和数据列表
解决方法
现有代码错误点
- 语法错误:
getData3方法中重复定义了String myUrl,删除多余的一行即可 - 逻辑错误:接口返回的JSON结构中,
user_f_name等用户字段存放在顶层data字段对应的数组内,并非在JSON根节点,直接调用data1['user_f_name']无法匹配到对应字段 - 兼容问题:你给出的JSON示例中第一条数据的
created_at字段缺少双引号,需确保服务端返回格式正确,避免解析异常
创建Dart Model类
手动编写解析逻辑即可,无需引入额外工具:
class UserResponse { final bool success; final String message; final List<User> data; UserResponse({required this.success, required this.message, required this.data}); factory UserResponse.fromJson(Map<String, dynamic> json) { var dataList = json['data'] as List; List<User> users = dataList.map((item) => User.fromJson(item)).toList(); return UserResponse( success: json['success'], message: json['message'], data: users, ); } } class User { final String userName; final String userFName; final String compType; final String compDepr; final String compCode; final String deprJob; final String compCodeSub; final String private1; final String private2; final String createUser; final String updateUser; final String createdAt; final String updatedAt; final int id; User({ required this.userName, required this.userFName, required this.compType, required this.compDepr, required this.compCode, required this.deprJob, required this.compCodeSub, required this.private1, required this.private2, required this.createUser, required this.updateUser, required this.createdAt, required this.updatedAt, required this.id, }); factory User.fromJson(Map<String, dynamic> json) { return User( userName: json['user_name'] ?? '', userFName: json['user_f_name'] ?? '', compType: json['comp_type'] ?? '', compDepr: json['comp_depr'] ?? '', compCode: json['comp_code'] ?? '', deprJob: json['depr_job'] ?? '', compCodeSub: json['comp_code_sub'] ?? '', private1: json['private_1'] ?? '', private2: json['private_2'] ?? '', createUser: json['create_user'] ?? '', updateUser: json['update_user'] ?? '', createdAt: json['created_at'].toString(), updatedAt: json['updated_at'] ?? '', id: json['id'] ?? 0, ); } }
修改获取用户列表的方法
Future<List<User>> getUserList() async { final prefs = await SharedPreferences.getInstance(); final token = prefs.getString('token') ?? ''; String myUrl = "$serverUrl/userchecks"; http.Response response = await http.get(Uri.parse(myUrl), headers: { 'Accept': 'application/json', 'Authorization': 'Bearer $token' }); if (response.statusCode == 200) { UserResponse res = UserResponse.fromJson(json.decode(response.body)); // 如需打印测试直接取对应字段即可 print('第一个用户的user_f_name: ${res.data.first.userFName}'); // 返回的列表可直接传给ListView.builder渲染 return res.data; } else { throw Exception('请求失败'); } }
修改获取单条用户数据的方法
Future<User?> getSingleUser() async { final prefs = await SharedPreferences.getInstance(); final token = prefs.getString('token') ?? ''; final username = prefs.getString('user') ?? ''; String myUrl = "$serverUrl/userchecks/$username"; http.Response response = await http.get(Uri.parse(myUrl), headers: { 'Accept': 'application/json', 'Authorization': 'Bearer $token' }); if (response.statusCode == 200) { UserResponse res = UserResponse.fromJson(json.decode(response.body)); if (res.data.isNotEmpty) { User currentUser = res.data.first; // 如需打印测试直接取对应字段即可 print('当前用户的user_f_name: ${currentUser.userFName}'); return currentUser; } return null; } else { throw Exception('请求失败'); } }
内容的提问来源于stack exchange,提问作者murat murat
相关产品推荐
相关产品推荐

