【问题标题】:How to add document Id in the document in firestore database in flutter application如何在flutter应用程序的firestore数据库中的文档中添加文档ID
【发布时间】:2025-12-06 22:25:01
【问题描述】:

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

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

【问题讨论】:

    标签: firebase flutter google-cloud-firestore


    【解决方案1】:

    DocumentReference docRef = await Firestore.instance.collection("products").add({

     'description': product.description,
     'imageUrl': product.imageUrl,
     'price': product.price,
    });
    final newProduct = Product(
     title: product.title,
     description: product.description,
     price: product.price,
     imageUrl: product.imageUrl,
     id:docRef.documentID,
    );
    
    _items.add(newProduct);
    

    【讨论】:

    • 这是两次添加不同 id 的条目,'Doug Stevenson' 解决方案是正确的,只需更改 DocumentReference ref = Firestore.instance.collection("posts1").document(); to: DocumentReference ref = Firestore.instance.collection("posts1").add({});
    【解决方案2】:

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

    DocumentReference ref = Firestore.instance.collection("posts1").document();
    ref.setData({
        "post_id": ref.documentID,
        // ... add more fields here
    })
    

    【讨论】: