Irfan Ganatra
Irfan Ganatra

Reputation: 1346

How to count number of messages in firebasefirestore collection in flutter

enter image description hereI 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;
  }

Upvotes: 0

Views: 540

Answers (3)

Việt Cao
Việt Cao

Reputation: 11

You can count 'new_message' for each message in a conversation. Change 'new_message' for current user and friends. Return count to 0 when user visits.

enter image description here

Upvotes: 0

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;

Upvotes: 1

Dishant Rajput
Dishant Rajput

Reputation: 1357

Delete your whole chat via 'ChatRoomId'

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

      });

Upvotes: 1

Related Questions