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

Obtain Document ID immediately after you create a new document with Set in Firebase Flutter

In my app I need to get the document ID for a document I just created.

I am creating the new document with:

db.collection('Pack').doc().set({
                    'userId': userID,
                    'packName': newPackNameController.text.trim(),
                    'description': newPackDescriptionController.text.trim(),
                    //todo: need to calculate new weight or grab from this pack...
                    'totalWeight': '0.0',
                    'weightFormat': weightFormat,
                  });

Next I need to document ID.

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

I tried this based on another stack overflow question:

DocumentReference docRef = await 
Firestore.instance.collection('gameLevels').add(map);
print(docRef.documentID);

But that was for adding a collection and not a document and I could not get the same code to work with a document.

>Solution :

The call to doc() is a pure client-side operation, so you can split it from the set():

var ref = db.collection('Pack').doc();
print(ref.id);
ref.set({
  'userId': userID,
  'packName': newPackNameController.text.trim(),
  'description': newPackDescriptionController.text.trim(),
  //todo: need to calculate new weight or grab from this pack...
  'totalWeight': '0.0',
  'weightFormat': weightFormat,
});

Also see the last code sample in the documentation on adding a document.

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