Skip to content Skip to sidebar Skip to footer

How To Fix 'getter "documents" Was Called On Null.' In Flutter

I am using flutter and firebase to create a mobile app. I have 2 collections on my firestore and i wanna read all documents in a the collection 'posts'. However, when I do that, an

Solution 1:

You should check that the snapshot.data is not null before you call snapshot.data.documents. This is often the first thing I do in the build method of a stream builder. If the stream is empty, like it will be when it is first listened to but before firestore has returned the data being requested, the snapshot.data will be null. In that case you might want to show a container or a circular progress indicator:

Widget getContent(BuildContext context) {
  return StreamBuilder<QuerySnapshot>(
    stream: Firestore.instance.collection("posts").snapshots(),
    builder: (context, snap) {

      //just add this line
      if(snap.data == null) return CircularProgressIndicator();

      return CarouselSlider(
        enlargeCenterPage: true,
        height: MediaQuery.of(context).size.height,
        items: getItems(context, snap.data.documents),
    );
    },
    );
}

List<Widget> getItems(BuildContext context, List<DocumentSnapshot> 
docs){
  return docs.map(
    (doc) {
      String content = doc.data["content"];
      return Text(content);
    }
  ).toList();
}

Post a Comment for "How To Fix 'getter "documents" Was Called On Null.' In Flutter"