【发布时间】:2019-08-15 03:58:02
【问题描述】:
如何使用 Dart 和 Flutter 添加具有自定义 id 的新文档?
PS:我可以将新文档添加到集合中,但它的 id 随机设置,使用此代码
postRef.add(data);其中
postRef是CollectionReference和data是Map<String, dynamic>
【问题讨论】:
标签: dart flutter google-cloud-firestore
如何使用 Dart 和 Flutter 添加具有自定义 id 的新文档?
PS:我可以将新文档添加到集合中,但它的 id 随机设置,使用此代码
postRef.add(data);其中
postRef是CollectionReference和data是Map<String, dynamic>
【问题讨论】:
标签: dart flutter google-cloud-firestore
您可以使用set() 函数代替add()。
这里是完整的代码:
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);
希望对大家有所帮助。
【讨论】:
await postsRef.add(postData);,这就是问题所在!
不要使用add,而是在文档上使用set。
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);
【讨论】:
Firestore.instance.runTransaction((Transaction tx) async { await _firestoreRef.setData(data); });
您可以尝试使用此代码插入带有 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"));
【讨论】: