skip to Main Content

I am checking if a chat collection already exists in Cloud Firestore:

 CollectionReference chats = FirebaseFirestore.instance.collection('chats');

 void checkUser() async {
    await chats
        .where('users', isEqualTo: {widget.emailOtro: null, usuario!.email: null})
        .limit(1)
        .get()
        .then(
          (QuerySnapshot querySnapshot) async {
        if (querySnapshot.docs.isNotEmpty) {
          setState(() {
            chatDocId = querySnapshot.docs.single.id;
            existeChatroom = true;
          });

          print(chatDocId);
        } else {
          existeChatroom = false;
          await chats.add({
            'users': {usuario!.email: null, widget.emailOtro: null},
            'names':{usuario!.email:miAlias,widget.emailOtro:widget.aliasOtro }
          }).then((value) {
            print("chat id recibido ${value}");
            chatDocId = value;
           
            });
        }
      },
    )
        .catchError((error) {});
  }

After checking if the collection chat has a doc with the selected users, the function should return the doc id as chatDocId

In the case that the chat document exists, I am getting the right chatDocId value.

But in the case that the chat document doesn’t exist, a new chat document is created but then I am not able to get the id from the document.

I am getting for chatDocId the value:

DocumentReference<Map<String, dynamic>>(chats/NSEgC8LvBOMfjP1Hw1IR

How can I get the document Id from the just created document?

2

Answers


  1. The document reference has a id field according to the documentation: https://pub.dev/documentation/cloud_firestore/latest/cloud_firestore/DocumentReference/id.html

    If I am not mistaken you can also see that in the String representation of the object: DocumentReference<Map<String, dynamic>>(chats/NSEgC8LvBOMfjP1Hw1IR, more explicitly NSEgC8LvBOMfjP1Hw1IR

    Login or Signup to reply.
  2. you can get the id directly from the returned value;

    .then((value) {
                print("chat id recibido ${value}");
                chatDocId = value;
                
                final chatId = value.id;
                print(chatId);
               
                });
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search