48

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>

0

4 Answers 4

67

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.

Sign up to request clarification or add additional context in comments.

6 Comments

Is it possible to create autoID?
Yes sure, you can use await postsRef.add(postData); that was the question really !
from where do we bring '.toJson();' ?? it's not defined and would be cool instead of what i'm doing not is I take every class like Post() and map its fields into a map,, if .toJson(); work automatically would be cool,, from where can I import that ? or I just define that function like I'm already doing ?
@RagehElAzzazy it's a method I defined in tge class, to return a map with keys an fields I want. No difference between my code and your code, just it's a method in class.
@Shady Boshra, I did the same, thanks man, teslam ya m3allem
|
11

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

Comments

3
String uniqueCode = //Your Unique Code DocumentReference reference = Firestore.instance.document("test/" + uniqueCode ); //Setting Data Map<String, String> yourData; reference.setData(yourData); 

1 Comment

This works too but If its a shared database I would recommend handling the atomicity by making each transaction atomic as follows Firestore.instance.runTransaction((Transaction tx) async { await _firestoreRef.setData(data); });
2

You can try this code to insert new Document with customID

 DocumentReference<Map<String, dynamic>> users = FirebaseFirestore .instance .collection('/users') .doc("MyCustomID"); var myJSONObj = { "FirstName": "John", "LastName": "Doe", }; users .set(myJSONObj) .then((value) => print("User with CustomID added")) .catchError((error) => print("Failed to add user: $error")); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.