skip to Main Content

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;
  }

2

Answers


  1. Delete your whole chat via ‘ChatRoomId

    FirebaseFirestore.instance
       .collection("chatrooms/'your_chat_room_id'")
              
       .delete()
        .then((value_2) {
       print('========> successfully deleted');
    
          });
    
    Login or Signup to reply.
  2. 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;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search