'How do you get the document id after adding document in Cloud Firestore in Dart

Im using the following code to update a Cloud Firestore collection using Dart/Flutter.

  final docRef = Firestore.instance.collection('gameLevels');
  docRef.document().setData(map).then((doc) {
    print('hop');
  }).catchError((error) {
    print(error);
  });

I'm trying to get the documentID created when I add the document to the collection but the (doc) parameter comes back as null. I thought it was supposed to be a documentReference?

Since it's null, I obviously can't use doc.documentID.

What am I doing wrong?



Solution 1:[1]

You can try the following:

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

Since add() method creates new document and autogenerates id, you don't have to explicitly call document() method

Or if you want to use "then" callback try the following:

  final collRef = Firestore.instance.collection('gameLevels');
  DocumentReferance docReference = collRef.document();

  docReferance.setData(map).then((doc) {
    print('hop ${docReferance.documentID}');
  }).catchError((error) {
    print(error);
  });

Solution 2:[2]

@Doug Stevenson was right and calling doc() method will return you document ID. (I am using cloud_firestore 1.0.3)

To create document you just simply call doc(). For example I want to get message ID before sending it to the firestore.

  final document = FirebaseFirestore.instance
      .collection('rooms')
      .doc(roomId)
      .collection('messages')
      .doc();

I can print and see document's id.

print(document.id)

To save it instead of calling add() method, we have to use set().

  await document.set({
    'id': document.id,
    'user': 'test user',
    'text': "test message",
    'timestamp': FieldValue.serverTimestamp(),
  });

Solution 3:[3]

Using value.id ,You can fetch documentId after adding to FireStore .

CollectionReference users = FirebaseFirestore.instance.collection('candidates');
  

      Future<void> registerUser() {
     // Call the user's CollectionReference to add a new user
         return users.add({
          'name': enteredTextName, // John Doe
          'email': enteredTextEmail, // Stokes and Sons
          'profile': dropdownValue ,//
          'date': selectedDate.toLocal().toString() ,//// 42
        })
            .then((value) =>(showDialogNew(value.id)))
            .catchError((error) => print("Failed to add user: $error"));
      }

Solution 4:[4]

If the Dart APIs are anything like other platforms, the document() method should return a document reference that has an id property with the randomly generated id for the document that's about to be added to the collection.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Doug Stevenson
Solution 2 ShadeToD
Solution 3 Rahul Kushwaha
Solution 4 Doug Stevenson