Solved: Firestore / Flutter - How can I get document Id?

Question

Asked by Hanna on December 04, 2018 (source).

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

Answer

Question answered by diegoveloper (source).

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 
FIREBASE FLUTTER GOOGLE-CLOUD-FIRESTORE
SHARE: