How to add new document with custom id using Dart and Flutter?
PS: I can add new document to collection but its id sets randomly, using this code
postRef.add(data);
which
postRef
isCollectionReference
anddata
isMap<String, dynamic>
Set the data of a document within a collection, explicitly specifying a document identifier. Add a new document to a collection. In this case, Cloud Firestore automatically generates the document identifier. Create an empty document with an automatically generated identifier, and assign data to it later.
There is no API to change the ID of an existing document, nor is there an API to move a document. If you want to store the same contents in a different document, you will have to: Read the document from its existing key. Write the document under its new key.
Future<String> get_data(DocumentReference doc_ref) async { DocumentSnapshot docSnap = await doc_ref. get(); var doc_id2 = docSnap. reference. documentID; return doc_id2; } //To retrieve the string String documentID = await get_data();
You can use set()
function instead of add()
.
Here's full code:
final CollectionReference postsRef = Firestore.instance.collection('/posts'); var postID = 1; Post post = new Post(postID, "title", "content"); Map<String, dynamic> postData = post.toJson(); await postsRef.doc(postID).set(postData);
I hope that help anyone.
Instead of using add
, use set
on the document.
var collection = FirebaseFirestore.instance.collection('collection'); collection .doc('doc_id') // <-- Document ID .set({'age': 20}) // <-- Your data .then((_) => print('Added')) .catchError((error) => print('Add failed: $error'));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With