如何在flutter应用程序中的firestore数据库的文档中添加文档Id

1 firebase flutter google-cloud-firestore

我使用下面的代码在 flutter 应用程序中的 firestore 集合中添加文档。我不知道如何在文档中添加文档 ID。请指导我

    Firestore.instance.collection("posts1").add({
                    //"id": "currentUser.user.uid",
                    "postTitle": posttitle.text,
                    "postcategory": selectedCategory,
                    "post_id":documentId,
                      })
                      .then((result) =>
                  {print("success")}
Run Code Online (Sandbox Code Playgroud)

Dou*_*son 6

使用document()不带参数的方式首先生成对具有随机 ID 的文档的引用,然后使用setData()它来创建它并将其添加documentID为新文档的一部分:

final DocumentReference ref = 
    FirebaseFirestore.instance.collection("posts1").doc();

await ref.setData({
  "post_id": ref.documentID,
  // ... add more fields here
});
Run Code Online (Sandbox Code Playgroud)