迁移到 null safety 后无法从 firestore 保存模型中的数据
Unable to save the data in model from firestore after migrating to null safety
所以,我有一个用户模型,我想在其中存储 firestore 中存在的文档的值,为此我有以下代码:-
import 'package:cloud_firestore/cloud_firestore.dart';
class UserModel
{
final String? id;
final String? username;
final String? email;
final String? url;
final String? androidNotificationToken;
UserModel({
this.id,
this.username,
this.email,
this.url,
this.androidNotificationToken,
});
factory UserModel.fromDocument(DocumentSnapshot doc)
{
return UserModel(
id: doc.data()['id'], //error
username: doc.data()['username'],//error
email: doc.data()['email'],//error
url: doc.data()['url'],//error
androidNotificationToken: doc.data()['androidNotificationToken'],//error
);
}
}
我面临的错误是 doc.data() 后的方括号中有一条红线显示错误,如我的代码中所标记。
错误是:-
The method '[]' can't be unconditionally invoked because the receiver can be 'null'.
我发现的一个修复方法是将 doc.data()['id'] 替换为 (doc.data() as dynamic)['id]。那么这是最好的方法吗?
你应该替换:
doc.data() as dynamic['id']
与:
doc.data() as Map<String, dynamic>['id']
DocumentSnapshot.data 属于 Map<String, dynamic>
.
类型
查看 migration guide cloud_firestore 2.0.0
。
所以,我有一个用户模型,我想在其中存储 firestore 中存在的文档的值,为此我有以下代码:-
import 'package:cloud_firestore/cloud_firestore.dart';
class UserModel
{
final String? id;
final String? username;
final String? email;
final String? url;
final String? androidNotificationToken;
UserModel({
this.id,
this.username,
this.email,
this.url,
this.androidNotificationToken,
});
factory UserModel.fromDocument(DocumentSnapshot doc)
{
return UserModel(
id: doc.data()['id'], //error
username: doc.data()['username'],//error
email: doc.data()['email'],//error
url: doc.data()['url'],//error
androidNotificationToken: doc.data()['androidNotificationToken'],//error
);
}
}
我面临的错误是 doc.data() 后的方括号中有一条红线显示错误,如我的代码中所标记。 错误是:-
The method '[]' can't be unconditionally invoked because the receiver can be 'null'.
我发现的一个修复方法是将 doc.data()['id'] 替换为 (doc.data() as dynamic)['id]。那么这是最好的方法吗?
你应该替换:
doc.data() as dynamic['id']
与:
doc.data() as Map<String, dynamic>['id']
DocumentSnapshot.data 属于 Map<String, dynamic>
.
查看 migration guide cloud_firestore 2.0.0
。