Im new to flutter and faced this error i know not why.. I tried extracting the StreamBuilder widget out of the chat_screen class and giving it a separate space but that also didn’t work. I have tried all the annotation suggestions it gives like putting an ‘!’ or ‘?’ before the snapshot.data.docs but it only recognizes till snapshot.data, even though it does give suggestions of docs command but after the ending ‘;’ it throws this error. I have been struggling with this since yesterday please help..
class MessageBuilder extends StatelessWidget {
const MessageBuilder({super.key});
@override
Widget build(BuildContext context) {
return StreamBuilder<QuerySnapshot>(
stream: _firestore.collection('messages').snapshots(),
builder: (context, snapshot) {
if (snapshot.data.docs!) {
return Center(
child: CircularProgressIndicator(
backgroundColor: Colors.lightBlueAccent,
),
);
} else {
List<QueryDocumentSnapshot<Object?>> messages = snapshot.data.docs;
List<Text> messageWidgets = [
Text('hello'),
];
if (messages == null) {
for (var message in messages) {
final messageText = message.data['text'];
final messageSender = message.data['sender'];
final messageWidget = Text('$messageText from $messageSender');
messageWidgets.add(messageWidget);
}
return Column(
children: messageWidgets,
);
}
}
},
);
}
}
I have initialized the line final _firestore = FirebaseFirestore.instance;
globally.
Here is the screenshot of the error im getting.It suggests the "docs" command but as soon as i use it..
2
Answers
Try this code:
Using
if (snapshot.data.docs!)
seems incorrect as both data and docs could be null.It is because the
snapshot.data
can be a null value, add a?
likesnapshot.data?.docs
if you want to use it, this is my demo code: