Flutter Firestore add new document with Custom ID

别来无恙 提交于 2020-08-03 15:28:31

问题


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>


回答1:


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.document(postID).setData(postData);

I hope that help anyone.




回答2:


String uniqueCode = //Your Unique Code
DocumentReference reference = Firestore.instance.document("test/" + uniqueCode );

//Setting Data
Map<String, String> yourData;
reference.setData(yourData);


来源:https://stackoverflow.com/questions/55328838/flutter-firestore-add-new-document-with-custom-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!