8
votes

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?

4

4 Answers

21
votes

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

@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(),
  });
3
votes

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"));
      }
1
votes

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.