首页 > 解决方案 > Flutter Firestore 添加具有自定义 ID 的新文档

问题描述

如何使用 Dart 和 Flutter 添加具有自定义 id 的新文档?

PS:我可以使用此代码将新文档添加到集合中,但其 id 随机设置

postRef.add(data);

postRefCollectionReferencedataMap<String, dynamic>

标签: dartfluttergoogle-cloud-firestore

解决方案


您可以使用set()function 而不是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);

我希望对任何人都有帮助。


推荐阅读