【发布时间】:2021-02-17 08:28:45
【问题描述】:
我已将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'], // unable to understand why it shows error here
username:map['username'],
email:map['email'],
phone:map['phone'],
);
}
Map<String, dynamic> toMap(){
return {
'id': id,
'username': username,
'email': email,
'phone': phone,
};
}
}
我可以登录并注册一个用户,但是这个错误一直出现在我的模型类 UserModel.fromJSON() 方法中我从 mongo db 的 _id to id 映射。这是错误:
I/flutter (19353): NoSuchMethodError: The method '[]' was called on null.
I/flutter (19353): Receiver: null
I/flutter (19353): Tried calling: []("_id")
有谁知道我需要对我的 UserModel 类进行哪些更改?谢谢。
【问题讨论】: