0

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

Update: the function I have tried based on Frank's answer:

 var docId = uid
        .toString()
        
        .compareTo(FirebaseAuth.instance.currentUser!.uid) > 0;

the function used for printing docId:

    IconButton(
              icon: Icon(Icons.send),
              iconSize: 20.0,
              onPressed: () async { print(docId);}
            )
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807

1 Answers1

1

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

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807