当我使用此代码时:
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'],
);}}
答案 0 :(得分:0)
使用这个访问它:
snapshot.data?.docs
因为快照中的数据可能为空,这就是我们在未来的构建器中检查 snapshot.hasData
是否为真的原因。