0

snapshot.data.documents[][]

Widget build(BuildContext context) {
   return Scaffold(
     body: StreamBuilder(
       stream:Firestore.instance.collection('chats/wuQaqmmo64XVBVJ6S6ET/messages')
           .snapshots()
       ,builder: (ctx,snapshot) {
         if(snapshot.connectionState == ConnectionState.waiting){
           return Center(
             child: CircularProgressIndicator(),
           );
         }

       return ListView.builder(
         itemCount: 5,
           itemBuilder: (ctx, index) =>
             Container(
               padding: EdgeInsets.all(8)
               , child: Text(snapshot.data.documents[0]['text']),
             ),
       );
     }

This is showing an error --The property 'documents' can't be unconditionally accessed because the receiver can be 'null'. And there is no any property of documents in flutter now?

smotastic
  • 388
  • 1
  • 11

1 Answers1

0

This error tells you that the data property of snapshot can be null. So you are not allowed to access documents of data without explicitly telling dart that data is never null.

if(snapshot.data != null) {
  // now you can access
  snapshot.data.documents;
}

Or if you are sure that the data is never null you can directly access it.

snapshot.data!.documents

See also https://dart.dev/null-safety/understanding-null-safety

More documentation on this specific error:

smotastic
  • 388
  • 1
  • 11
  • It didnt work though,still facing same! i cant use documents in this code - snapshot.data!.documents Help me! – Lokesh Acharya Aug 17 '21 at 14:01
  • What is the error now? Still the same or another property? I’m assuming the problem now is the array access. You are accessing the text key without checking if it exists before. Try „.data[0][„text“]!“ ( am on mobile will Format later) – smotastic Aug 17 '21 at 14:37
  • only error is that ,there we can't use "documents" as a property.so in substitute what I property should I use! while writing snapshot.data. ---- now here ---- there is no suggestion of documents[] but I have to use documents to fetch data. Hope u understand my problem! – Lokesh Acharya Aug 18 '21 at 09:15
  • According to the documentation on Firestore (https://firebase.flutter.dev/docs/overview) ( assuming you are using this ) the QuerySnapshot which you are retrieving out of the CollectionReference doesn't have a data Property. I think you want to use `docs`. See https://pub.dev/documentation/cloud_firestore/latest/cloud_firestore/QuerySnapshot-class.html – smotastic Aug 18 '21 at 10:23