firestore getter 'length' 没有为类型 'DocumentSnapshot<Object?>' 定义

firestore the getter 'length' isn't defined for the type 'DocumentSnapshot<Object?>'

我尝试在 firestore 中计算来自一个用户的所有文档。 我的代码:

  Widget booksWidget(String userData) {                            
    return
    StreamBuilder(
        stream: FirebaseFirestore.instance
            .collection("bookList")
            .doc(userData)
            .collection(userData)
            .orderBy("timestamp", descending: true)
            .snapshots(),
        builder: (BuildContext context,AsyncSnapshot snapshot)  {
          if (snapshot.hasData) {
            var userDocument = snapshot.data as DocumentSnapshot?;
            String books = userDocument?.length.toString();
            return Text(books);
          }else{
            return Text("none");
          }
        }
    );
  }

错误:

The getter 'length' isn't defined for the type 'DocumentSnapshot<Object?>'.

感谢您的帮助,迁移到 null-safety 后的 streambuilder 大不相同:(

您正在请求查询的快照,因此您获得的 snapshot.data 将是 QuerySnapshot 类型(而不是您现在假设的 DocumentSnapshot? 类型) .

if (snapshot.hasData) {
  var querySnapshot = snapshot.data! as QuerySnapshot;
  String books = querySnapshot.docs.length.toString();
  ...

在这种情况下,我发现使用参考文档最容易,例如此处 Query.snapshots() 的参考文档。