Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firestore / Flutter - How can I get document Id?

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

like image 313
Hanna Avatar asked Dec 04 '18 04:12

Hanna


People also ask

How do I get info from Firebase Flutter?

To use Flutter with Firebase, you will first need to set dependencies in the pubspec file. You will also have to import firestore , i.e., the database provided by Firebase for data handling. Now, import the Firebase dependencies into your Dart file. import 'package:cloud_firestore/cloud_firestore.

What is document reference in Flutter?

A DocumentReference refers to a document location in a FirebaseFirestore database and can be used to write, read, or listen to the location. The document at the referenced location may or may not exist. A DocumentReference can also be used to create a CollectionReference to a subcollection.


1 Answers

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 
like image 54
diegoveloper Avatar answered Oct 07 '22 00:10

diegoveloper