简体   繁体   中英

How to count number of messages in firebasefirestore collection in flutter

在此处输入图像描述 I am trying to make a chat app with the help of a channel,

there is a search page where I search user to chat,

If I tap on user, a new windows will be created if no previous chat found,

and if not chatting first time, will use existing chatroom

code is running well, but I want some implement,

if I search a user and tap on him, and than I go back without chatting, created new room should be deleted.... so that I need number of message's logic...

how to implement to achieve it

Future<ChatRoomModel?> getchatroom(UserModel targetuser) async {
    ChatRoomModel? chatroom;

    //here i feel something wrong as even if blocked chatroom, window should be open
    QuerySnapshot querysnapshot = await FirebaseFirestore.instance
        .collection("chatrooms")
        .where("participants.${targetuser.uid}", isEqualTo: true)
        .where("participants.${widget.userModel.uid}", isEqualTo: true)
        .get();

    if (querysnapshot.docs.length > 0) {
      var docdata = querysnapshot.docs[0].data();

      ChatRoomModel existingchatroom =
          ChatRoomModel.fromMap(docdata as Map<String, dynamic>);

      chatroom = existingchatroom;
    } else {
      //creating new chat room
      ChatRoomModel newchatroommodel = ChatRoomModel(
          chatroomid: DateTime.now().toString(),
          participants: {
            widget.userModel.uid.toString(): true,
            targetuser.uid.toString(): true,
          },
          lastMessage: "Say Hi");

      await FirebaseFirestore.instance
          .collection("chatrooms")
          .doc(newchatroommodel.chatroomid)
          .set(newchatroommodel.toMap());
      chatroom = newchatroommodel;
      print("Created success");
    }

    return chatroom;
  }

Delete your whole chat via ' ChatRoomId '

FirebaseFirestore.instance
   .collection("chatrooms/'your_chat_room_id'")
          
   .delete()
    .then((value_2) {
   print('========> successfully deleted');

      });

How is the messages stored in Firestore? Does each message have it's own document, or are they stored in a list inside ChatRoomModel?

Count your messages by retrieving a list of documents from your "messages" collection:

QuerySnapshot messages = await querysnapshot.docs[0].reference.collection("messages").get();
int messageCount = messages.size;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM