Firestore / Flutter - How can I get document Id?
18,129
Solution 1
After collection
you can add a document
and receive the DocumentReference
.
final docRef = await Firestore.instance.collection('product').add({
'name': nameController.text,
'price': int.tryParse(priceController.text),
'description': descriptionController.text,
'creator': widget.user.uid,
'created': DateTime.fromMillisecondsSinceEpoch(created.creationTimeMillis, isUtc: true).toString(),
'modified': DateTime.fromMillisecondsSinceEpoch(created.updatedTimeMillis, isUtc: true).toString(),
'url': downloadUrl,
});
Now you can get the document ID:
docRef.documentID
Solution 2
you do it like that
DocumentReference documentReference = Firestore.instance.collection('product').document();
documentReference.setData({
'name': nameController.text,
'price': int.tryParse(priceController.text),
'description': descriptionController.text,
'creator': widget.user.uid,
'created': DateTime.fromMillisecondsSinceEpoch(created.creationTimeMillis, isUtc: true).toString(),
'modified': DateTime.fromMillisecondsSinceEpoch(created.updatedTimeMillis, isUtc: true).toString(),
'url': downloadUrl,
'id': documentReference.documentID
});
Document ID
documentReference.documentID
Solution 3
Since v0.14.0 of the cloud_firestore package:
DEPRECATED: documentID has been deprecated in favor of id.
so instead of
ref.documentId
use
ref.id
to retriev the random generated document id.
Solution 4
You can get the ID by calling your ref.documentID
![Admin](/assets/logo_square_200-5d0d61d6853298bd2a4fe063103715b4daf2819fc21225efa21dfb93e61952ea.png)
Author by
Admin
Updated on June 22, 2022Comments
-
Admin about 2 years
this is my code
Future _save() async { final StorageReference storageRef = FirebaseStorage.instance.ref().child('product/'+nameController.text+'.jpg'); final StorageUploadTask task = storageRef.putFile(_image); StorageTaskSnapshot taskSnapshot = await task.onComplete; String downloadUrl = await taskSnapshot.ref.getDownloadURL(); StorageMetadata created = await taskSnapshot.ref.getMetadata(); Firestore.instance.collection('product').document() .setData({ 'name': nameController.text, 'price': int.tryParse(priceController.text), 'description': descriptionController.text, 'creator': widget.user.uid, 'created': DateTime.fromMillisecondsSinceEpoch(created.creationTimeMillis, isUtc: true).toString(), 'modified': DateTime.fromMillisecondsSinceEpoch(created.updatedTimeMillis, isUtc: true).toString(), 'url': downloadUrl, 'id': //I want to set document Id here // }); }
how can I get this random generated document's ID? Thank you for your help