I am building a simple chat app using Flutter and Firestore. I have the app working but I am having difficulty implementing the unread message counter to feed the Navbar. I am using Badges to place a number alongside the Messages icon, but I am not sure of the best way to determine the unread message count from the Chats collection in Firestore.
I know how to determine the unread count from my chat collection, but I am not sure of the most effective way to get the data. I tried to create a Stream but run into challenges implementing that approach. Here is the code that I used to create the Stream. I am getting the data, but I am having a challenge parsing it so I can determine the unread count. Here is my Stream code:
FirebaseFirestore.instance.collection('chats')
.where('users', arrayContains: currentUserReference)
.snapshots()
.listen((QuerySnapshot querySnapshot){
querySnapshot.docs.forEach((document) {
print(document.data());
});
}
);
flutter: {user_a: DocumentReference<Map<String, dynamic>>(users/1a305sQhd2MmQsIVsposE0AHto52), last_message_time: Timestamp(seconds=1644323419, nanoseconds=16000000), user_b: DocumentReference<Map<String, dynamic>>(users/277amBvOk4cfydxdEkZvs4Od31C2), last_message_sent_by: DocumentReference<Map<String, dynamic>>(users/1a305sQhd2MmQsIVsposE0AHto52), last_message_seen_by: [DocumentReference<Map<String, dynamic>>(users/277amBvOk4cfydxdEkZvs4Od31C2)], users: [DocumentReference<Map<String, dynamic>>(users/1a305sQhd2MmQsIVsposE0AHto52), DocumentReference<Map<String, dynamic>>(users/277amBvOk4cfydxdEkZvs4Od31C2)], last_message: are you there?}
I am not sure if my Stream approach is correct, and I don't know how to parse the above result so I can determine the unread count. I will determine the unread count by checking the number of instances of where the currentUser id is contained in the 'last_message_seen_by' field.
I would appreciate any guidance on how to approach this task.