Reputation: 187
I'd like to show the number of unread messages on chat icon in a page of my flutter-firestore app.
For that, I save unread message docId
s inside each chatRoomId
. I can count each number for each chatRoomId
respectively, but can't count all number for all chatRoomId
s to show total number of unread messages of a user like in above picture.
The following is my firestore structure. For example, as you see in the screenshot, if I want to count all docId
s and create 3
in a red circle on the chat badge, how can I do that in code?
Here is what I can do so far to create that badge count.
int _getUnseenMessagesNumber(List<Map<String, dynamic>> items) {
int counter = 0;
for (final item in items) {
counter += item.values.first.length;
}
return counter;
}
body: StreamBuilder<DocumentSnapshot>(
stream: FirebaseFirestore.instance
.collection('crews')
.doc(uid)
.snapshots(),
builder: (context, snapshot) {
int number = _getUnseenMessagesNumber(
snapshot.data['chatRoomIds']);
if (snapshot.data['chatRoomIds'].isNotEmpty) {
return Stack(children: [
Container(
decoration: BoxDecoration(
shape: BoxShape.circle, color: Colors.red),
child: Center(
child: Text(
number.toString()
),
),
]);
} else {
return container();
}
}),
Upvotes: 1
Views: 2073
Reputation: 839
ok then if you changed the structure of your document so that the unseen messages are in a list of Map, then should be able to extract the number of unseen messages with some function like this:
int _getUnseenMessagesNumber(List<Map<String, dynamic>> items){
int counter = 0;
for(final item in test) {
counter+=item.values.first.length;
}
return counter;
}
I hope it helped
Upvotes: 1