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>
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>
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'));
String uniqueCode = //Your Unique Code
DocumentReference reference = Firestore.instance.document("test/" + uniqueCode );
//Setting Data
Map<String, String> yourData;
reference.setData(yourData);
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"));