i will showing message from firebase firestore in flutter , but when i make conditional in snapshot always returning false this is my code
Service
Stream<List<MessageModel>> getMessagesByUserid({int userId}) {
try {
return firestore
.collection('messages')
.where('userId', isEqualTo: userId)
.snapshots()
.map((QuerySnapshot list) {
var result = list.docs.map<MessageModel>((DocumentSnapshot message) {
print('from service : ' + message.data().toString());
return MessageModel.fromJson(message.data());
}).toList();
result.sort(
(MessageModel a, MessageModel b) =>
a.createdAt.compareTo(b.createdAt),
);
return result;
});
} catch (e) {
throw Exception(e);
}
}
and call with this
Widget content() {
return StreamBuilder<List<MessageModel>>(
stream: MessageService()
.getMessagesByUserid(userId: authprovider.user.id),
builder: (context, snapshot) {
print(snapshot.hasData);
if (snapshot.hasData) {
return ListView(
padding: EdgeInsets.symmetric(
horizontal: defaultMargin,
),
children: snapshot.data
.map(
(MessageModel message) => ChatBubble(
isSender: message.isFromUser,
text: message.message,
product: message.product,
),
)
.toList(),
);
} else {
return Center(
child: CircularProgressIndicator(),
);
}
});
}
when i print in service , i get
I/flutter (29881): from service : {createdAt: 2021-06-28 16:29:25.106709, product: {}, userImage: https://ui-avatars.com/api/?name=eka&color=7F9CF5&background=EBF4FF, isFromUser: true, message: tanpa, userName: eka, userId: 2, updatedAt: 2021-06-28 16:29:25.106811}
but when i print(snapshot.hasData) always returning false
I/flutter (29881): false
If you require more granularity when using StreamBuilder
then test snapshot.connectionState
rather than snapshot.hasData
.
snapshot.hasData
can still be false if the Stream is returning null