How to have both sides view same chat in flutter

Viewed 29

I was following this tutorial https://www.youtube.com/watch?v=wHIcJDQbBFs&t= and got it working so I can send messages and it is stored as follows

chats/targetUid/messages/message

when I send a message it works and I can see them but if I sign into the account im sending it to they cannot see it. I believe its due to the following reasons.

In the tutorial you get data from the targets messages so when I open the chat its getting it from his Uid as the target but when he opens it it uses my Uid as the target.

This is my send message code.

//create Comment
    Message newMessage = Message(
      profImage: myProfilePic,
      username: myName,
      uid: myUid,
      message: message,
      createdAt: DateTime.now(),
    );

    final refMessages = _firestore.collection('chats/$targetUid/messages');

    await refMessages.add(
      newMessage.toJson(),
    );

The code to open the message.

return ListView.builder(
          itemCount: (snapshot.data! as dynamic).docs.length,
          itemBuilder: (context, index) {
            return InkWell(
              onTap: () {
                Navigator.of(context).push(
                  MaterialPageRoute(
                    builder: (context) => ChatScreen(
                      uid: (snapshot.data! as dynamic).docs[index]['uid'],
                    ),
                  ),
                );
              },
              child: ListTile(
                leading: CircleAvatar(
                  backgroundImage: NetworkImage(
                    (snapshot.data! as dynamic).docs[index]['photoUrl'],
                  ),
                ),
                title: Text(
                  (snapshot.data! as dynamic).docs[index]['username'],
                ),
              ),
            );
          },
        );
1 Answers

I fixed it by creating a groupchat Id and storing it in firestore that way rather than the targets Uid. this is the method im using to create the groupchat Id.

String chatroomId(String user1, String user2) {
    if (user1[0].toLowerCase().codeUnits[0] >
        user2.toLowerCase()[0].codeUnits[0]) {
      return "$user1$user2";
    } else {
      return "$user2$user1";
    }
  }
Related