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