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

Getting the id from a just created Firestore document

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.

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

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?

>Solution :

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);
           
            });
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