flutter对接Node/MongoDB:如何将JSON响应映射为UserModel类并解决_id映射报错
提问内容
后端采用Node/MongoDB实现,所有请求与响应交互流程正常。
前端使用Flutter开发移动应用,需要创建模型类对应接口返回的响应结构。登录接口的示例响应如下:
{ success: true, message: Logged in Successfully, user: { _id: 6028965c16056b37eca50076, username: spideyr, email: peterparker@gmail.com, password: $2b$10$R4kYBA3Ezk7z2EBIY3dfk.6Qy.IXQuXJocKVS5PCzLf4fXYckUMju, phone: 89066060484, __v: 0 }, accessToken: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOjE2MTM1NDg3ODIsImV4cCI6MTYxNjE0MDc4MiwiYXVkIjoiNjAyODk2NWMxNjA1NmIzN2VjYTUwMDc2IiwiaXNzIjoicGlja3VycGFnZS5jb20ifQ.DX8-WGRkCQ9geAaQASOIzoPGpvpjdI7aV0C5o1i5Thw, refreshToken: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOjE2MTM1NDg3ODIsImV4cCI6MTY0NTEwNjM4MiwiYXVkIjoiNjAyODk2NWMxNjA1NmIzN2VjYTUwMDc2IiwiaXNzIjoicGlja3VycGFnZS5jb20ifQ.RkVCGK9FfU0rxs2qf5QtJsyFaGShsL05CI320GsmAwg }
因为仅需关注user字段,因此编写了对应的POJO/PODO类:
class UserModel { final String id; final String username; final String email; final String phone; const UserModel({ this.id, @required this.email, @required this.username, @required this.phone, }); UserModel copyWith({String id, String username, String email, String phone}){ if ( (id == null) || identical(id, this.id) && (username == null) || identical(id, this.username) && (email == null || identical(email, this.email)) && (phone == null || identical(phone, this.phone))) { return this; } return new UserModel( id: id ?? this.id, username: username ?? this.username, email: email ?? this.email, phone: phone ?? this.phone, ); } static const empty = UserModel(email: '', username: null, phone: null, id: ''); @override String toString() { return 'User{id: $id, username: $username, email: $email, phone: $phone}'; } factory UserModel.fromMap(Map<String, dynamic> map){ return new UserModel( id:map['_id'], // 此处持续出现报错 username:map['username'], email:map['email'], phone:map['phone'], ); } Map<String, dynamic> toMap(){ return { 'id': id, 'username': username, 'email': email, 'phone': phone, }; } }
目前已可实现基础的用户登录与注册功能,但在模型类的fromMap方法中,将MongoDB返回的_id字段映射为模型id属性时,持续抛出错误,报错日志如下:
I/flutter (19353): NoSuchMethodError: The method '[]' was called on null. I/flutter (19353): Receiver: null I/flutter (19353): Tried calling: []("_id")
需要针对UserModel类做哪些修改才能解决上述问题?
排查与解决方案
报错根因
日志提示Receiver: null,说明传入UserModel.fromMap的map参数本身为null,并非读取某个key时返回空值。常见触发场景:
- 接口响应为嵌套结构,直接将外层整个响应Map传入
fromMap,没有先提取user对应的子对象 - 解析JSON时层级读取错误,从外层Map取
user字段时得到null,再将该空值传入fromMap
注:如果map本身是正常Map实例,即使读取的key不存在,也只会返回null值,不会触发空方法调用错误。
具体修改点
- 为
fromMap增加空值防护
在方法开头增加入参判断,避免对null实例直接调用[]操作:
factory UserModel.fromMap(Map<String, dynamic>? map) { // 入参为null时返回预定义的空模型实例 if (map == null) return UserModel.empty; return UserModel( id: map['_id'] ?? '', username: map['username'] ?? '', email: map['email'] ?? '', phone: map['phone'] ?? '', ); }
- 修正嵌套响应的解析流程
调用fromMap时,必须先从完整响应Map中提取user对应的子Map,再传入模型工厂方法,示例代码:
// 解析网络返回的完整响应字符串 final responseMap = jsonDecode(responseBody) as Map<String, dynamic>; // 提取user子对象并映射为模型实例 final user = UserModel.fromMap(responseMap['user'] as Map<String, dynamic>?);
- 修复原有代码的逻辑缺陷
- 原有
copyWith方法的判断存在运算符优先级错误,会导致逻辑失效、不必要的实例重建,修正后的逻辑:
UserModel copyWith({ String? id, String? username, String? email, String? phone, }) { // 所有字段均无变化时直接返回当前实例 if ( (id == null || identical(id, this.id)) && (username == null || identical(username, this.username)) && (email == null || identical(email, this.email)) && (phone == null || identical(phone, this.phone)) ) { return this; } return UserModel( id: id ?? this.id, username: username ?? this.username, email: email ?? this.email, phone: phone ?? this.phone, ); }
- 适配Dart空安全规则:所有可空属性需明确标注空可空类型,构造函数的必填参数需和
UserModel.empty的预定义参数匹配,避免编译期类型错误 - 根据实际接口交互需求调整
toMap的返回key:如果需要把模型数据回传给MongoDB,需将id对应的key改回_id,和数据库字段规则保持一致
内容的提问来源于stack exchange,提问作者Nzadibe
相关产品推荐
相关产品推荐

