如何解决无法无条件访问属性“docs”,因为接收者可以为“null”
当我使用此代码时:
return FutureBuilder(
future: searchResultsFuture,builder: (context,snapshot) {
if (!snapshot.hasData) {
return cargandoCircular();
}
List<UserResult> searchResults = [];
snapshot.data.docs.forEach((doc) {
User user = User.fromDocument(doc);
UserResult searchResult = UserResult(user);
searchResults.add(searchResult);
});
return ListView(
children: searchResults,);
我收到错误:
The property 'docs' can't be unconditionally accessed because the receiver can be 'null'.
Try making the access conditional (using '?.') or adding a null check to the target ('!').
添加空检查并不能解决任何问题,而且所有内容都在另一个 dart 文件的 User
类中声明,如下所示:
class User {
final String id;
final String username;
final String email;
final String photoUrl;
final String displayName;
final String bio;
User(
{required this.id,required this.username,required this.email,required this.photoUrl,required this.displayName,required this.bio});
factory User.fromDocument(DocumentSnapshot doc) {
return User(
id: doc['id'],email: doc['email'],username: doc['username'],photoUrl: doc['photoUrl'],displayName: doc['displayName'],bio: doc['bio'],);}}
解决方法
使用这个访问它:
snapshot.data?.docs
因为快照中的数据可能为空,这就是我们在未来的构建器中检查 snapshot.hasData
是否为真的原因。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。