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.

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.

Leave a Reply