【问题标题】:The property 'docs' can't be unconditionally accessed because the reciever can be 'null' [duplicate]无法无条件访问属性“文档”,因为接收者可以为“空”[重复]
【发布时间】:2021-09-21 03:40:23
【问题描述】:

当我使用这段代码时:

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'],
);}}

【问题讨论】:

标签: firebase flutter dart dart-null-safety


【解决方案1】:

使用这个访问它:

snapshot.data?.docs

因为快照中的数据可以为空,这就是为什么我们在未来的构建器中检查snapshot.hasData 是否为真。

【讨论】:

  • 当我添加 ?它抛出此错误:没有为类型“对象”定义吸气剂“文档”。尝试导入定义“docs”的库,将名称更正为现有 getter 的名称,或者定义一个名为“docs”的 getter 或字段。
  • 试试快照?.data.docs
猜你喜欢
  • 2021-09-21
  • 2021-07-13
  • 2022-08-15
  • 2021-08-05
  • 2022-01-11
  • 2022-08-15
  • 2021-11-21
  • 1970-01-01
  • 2021-09-05
相关资源
最近更新 更多