Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

error in saving two users chat in flutter

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading