How do you get the document id after adding document in Cloud Firestore in Dart
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"));
}
@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(),
});
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);
});