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

Issue

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 🙁

Solution

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.

Answered By – Frank van Puffelen

Answer Checked By – Terry (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *