没有为“AsyncSnapshot<Object?>”类型定义 getter 'docs'

时间:2021-06-13 06:07:17

标签: firebase flutter google-cloud-firestore flutter-futurebuilder

迁移到空安全后出现错误 未为类型“AsyncSnapshot”定义 getter 'docs'。 尝试导入定义“docs”的库,将名称更正为现有 getter 的名称,或者定义名为“docs”的 getter 或字段。

错误所在的代码片段

    return FutureBuilder(
      future: searchResultsFuture,
      builder: (context, snapshot) {
        if (!snapshot.hasData) {
          return circularProgress();
        }
        List<UserResult> searchResults = [];
        snapshot.docs.forEach((doc) {    //have error here
          User user = User.fromDocument(doc);
          UserResult searchResult = UserResult(user);
          searchResults.add(searchResult);
        });
        return ListView(
          children: searchResults,
        );
      },
    );
  } 

搜索结果未来


  handleSearch(String query) {
    Future<QuerySnapshot> users =
        usersRef.where("displayName", isGreaterThanOrEqualTo: query).get();
    setState(() {
      searchResultsFuture = users;
    });
  }

  clearSearch() {
    searchController.clear();
  }

2 个答案:

答案 0 :(得分:1)

您代码中的 snapshot 是一个 AsyncSnapshot,它确实没有 docs 子代。要从 Firestore 获取文档,您需要使用:

snapshot.data.docs

另请参阅 listening for realtime data 上的 FlutterFire 文档,其中包含显示此示例的示例 - 我的回答在这里解释了所有快照类型:What is the difference between existing types of snapshots in Firebase?

答案 1 :(得分:0)

通常,检索数据需要几毫秒的时间,所以我尝试这样做 确保在检索数据后执行我的操作

return StreamBuilder<QuerySnapshot>(
    stream: Collectionreference
        .snapshots(),
    builder: (BuildContext context,
        AsyncSnapshot<QuerySnapshot> activitySnapshot) {
      if (activitySnapshot.hasError) {
        return  Center(
              child: Text('Something went wrong'),
            );
      }
      if (activitySnapshot.connectionState == ConnectionState.waiting) {
        return Center(
                child: SpinKitWave(
              color: constants.AppMainColor,
              itemCount: 5,
              size: 40.0,
            )));
      }
      if (!activitySnapshot.hasData || activitySnapshot.data.docs.isEmpty) {
        return Center(
              child: Text('Nothing to Display here'),
            );
      }
      if (activitySnapshot.hasData) {
         activitySnapshot.data.docs.forEach(doc=>{
            print(doc);
          })
      }
     }
   });