Home > Back-end >  error in saving two users chat in flutter
error in saving two users chat in flutter

Time:05-02

I was making chat app in flutter with firebase. I was able to save the users chat in firebase by this function:

await FirebaseFirestore.instance
                        .collection("Chats")
                        .doc(uid!   FirebaseAuth.instance.currentUser!.uid)
                        .collection("messages")
                        .add({
                      FirebaseAuth.instance.currentUser!.uid:
                          chatController.text,
                      
                    }).then((value) => () {
                              b = uid;
                            });

but when I save the one users chat. I was thinking that when I will get the chat of second user. It will return a chat from the doc I was saving the both users chat. But unfortunately when I save the users chat it saves a new doc named first users id and then second users id, in first users chat it saves doc named the second user id and first users id. I know what is the reason from which it was happening but how can I resolve that, I mean how can I save the both users chat in one doc

CodePudding user response:

You need to have a deterministic ID for the document.

One simple way to do this is to always alphabetically order the two UIDs with something like this:

const docId = uid!.compareTo(FirebaseAuth.instance.currentUser!.uid) > 0 
  ? uid!   FirebaseAuth.instance.currentUser!.uid 
  : FirebaseAuth.instance.currentUser!.uid   uid! 

await FirebaseFirestore.instance
                        .collection("Chats")
                        .doc(docId)
                        ...

For more on this, see the examples in my answer here: Best way to manage Chat channels in Firebase

  • Related