Flutter / FireStore : Get the ID of the document just created in Collection

286

after adding a document you will get a document reference, with this reference you can get id, i don't know is that method names changed or not after new patches but solution must be similar to that

DocumentReference docRef = await 
FirebaseFirestore.instance
.collection('Users')
.doc(uid)
.collection('Accomodation')
.add(data);
print(docRef.documentID);
Share:
286
Admin
Author by

Admin

Updated on December 27, 2022

Comments

  • Admin
    Admin over 1 year

    I am adding data in Firestore with User > Accomodation collection. Firestore is automatically creating a new document in the collection Accomodation with all the details I haved added. But now I need to get the id of the document that he has just created to pass it to another screen. Should I create my own Accomodation ID or is there a way to get it ?

    FirebaseFirestore.instance
    .collection('Users')
    .doc(uid)
    .collection('Accomodation')
    .add(data);
    

    The User can have multiple Accomodation already created, I need to get the one just created.

    • Fer Buero Trebino
      Fer Buero Trebino over 3 years
      The User have an ID? You can use this ID and then access to the object inside.
    • Admin
      Admin over 3 years
      Yes the User has an ID, but he as multiple Accommodation already. I need the latest created.
    • Fer Buero Trebino
      Fer Buero Trebino over 3 years
      This depends on how you create the Acomodation colection in Firestore, but you should create this with Auto Id, so when a new is created already have an ID.
  • Admin
    Admin over 3 years
    Great, it works, thanks !! Correction : docRef.id