Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter Firestore add new document with Custom ID

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 is CollectionReference and data is Map<String, dynamic>

like image 270
Shady Boshra Avatar asked Mar 24 '19 21:03

Shady Boshra


People also ask

How do I get the document ID added to firestore?

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.

Can you change document ID firestore?

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.

How do I find my firestore document ID in Flutter?

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();


2 Answers

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.

like image 143
Shady Boshra Avatar answered Sep 24 '22 07:09

Shady Boshra


Update 2021:

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')); 
like image 32
CopsOnRoad Avatar answered Sep 20 '22 07:09

CopsOnRoad