【问题标题】:flutter-firestore: how to total unread messages for badge countflutter-firestore:如何汇总未读消息以进行徽章计数
【发布时间】:2021-06-07 08:43:59
【问题描述】:

我想在我的 flutter-firestore 应用页面的聊天图标上显示未读消息的数量。 为此,我将未读消息docIds 保存在每个chatRoomId 中。我可以分别计算每个chatRoomId 的每个数字,但不能计算所有chatRoomIds 的所有数字以显示用户的未读消息总数,如上图所示。 以下是我的 Firestore 结构。例如,如您在屏幕截图中看到的,如果我想计算所有docIds 并在聊天徽章上的红色圆圈中创建3,我该如何在代码中做到这一点?

到目前为止,我可以做以下事情来创建徽章计数。

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();
                }
              }),

【问题讨论】:

  • 您可以尝试使用 Map 数组,例如 [roomID: [docID1, Docid2], roomID2: [docID3],...] 而不是每次有一个新房间时都创建一个字段看不见的消息
  • @ArnaudDelubac 感谢 Amaud,我按照您的建议使用新的 Firestore 结构编辑了我的问题。现在如何更改我的代码以获得计算代码中'chatRoomIds' 字段中所有docIds 的结果?

标签: flutter google-cloud-firestore count


【解决方案1】:

那么,如果您更改了文档的结构,以便未看到的消息位于 Map 列表中,那么应该能够使用以下功能提取未看到的消息的数量:

int _getUnseenMessagesNumber(List<Map<String, dynamic>> items){
 int counter = 0;
 for(final item in test) {
    counter+=item.values.first.length;
 }
 return counter;
 }

希望对你有帮助

【讨论】:

  • 我用我的新代码编辑了我的问题。当我运行该应用程序时,我有一个错误提示 type '_internallinkedhashmap string dynamic ' is not a subtype of type 'list dynamic' 。我该如何解决这个问题?
  • 将 if (snapshot.data['chatRoomIds'].isNotEmpty) 更改为 if(snapshot.hasData) 并将行 intnumber = ... 放入 if 块中
猜你喜欢
  • 2021-07-09
  • 1970-01-01
  • 2014-05-21
  • 1970-01-01
  • 1970-01-01
  • 2021-05-08
  • 2015-12-06
  • 1970-01-01
  • 2013-09-29
相关资源
最近更新 更多