Home > Blockchain >  firestore the getter 'length' isn't defined for the type 'DocumentSnapshot<Ob
firestore the getter 'length' isn't defined for the type 'DocumentSnapshot<Ob

Time:02-11

I try to count all docs from one user in firestore. My code:

  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 error:

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

thanks for help, streambuilder after migration to null-safety is quite different :(

CodePudding user response:

You're requesting the snapshots of a query, so the snapshot.data that you get is going to be of type QuerySnapshot (and not a DocumentSnapshot? as you assume now).

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

In cases like this I find it easiest to work from the reference documentation, such as the one for Query.snapshots() here.

  • Related