【问题标题】:How to fetch auto generated document id in firebase firestore in flutter?如何在flutter中获取firebase firestore中自动生成的文档ID?
【发布时间】:2020-06-12 16:20:21
【问题描述】:

我怎样才能得到这个随机生成的文档的 ID?谢谢你的帮助

【问题讨论】:

  • 你的意思是在你添加了一个新的之后?
  • 要么你记得它被添加到你的代码中的时间,要么你根据文档的内容来查询它。如果不查看您的代码并了解您要完成的工作,就很难给出建议。请编辑问题以使其更清楚。

标签: firebase flutter dart google-cloud-firestore


【解决方案1】:

添加文档时可以得到documentId

  FirebaseFirestore.instance.collection("users").add(
  {
    "name" : "john",
    "age" : 50,
  }).then((value){
    print(value.id);
  });

【讨论】:

    【解决方案2】:

    如果您尝试从 Firestore 中读取数据,您可以通过以下方式获取整个集合 db.collection("users") 然后循环遍历返回的 querySnapshot 以获取每个返回的文档。您可以通过这种方式获得documentIDHere 是它的文档。

    db.collection("users").get().then(function(querySnapshot) {
        querySnapshot.forEach(function(doc) {
            var id = doc.id; // randomly generated document ID
            var data = doc.data(); // key-value pairs from the document
        });
    });
    

    【讨论】:

      【解决方案3】:

      查看您的代码很难给出准确的答案,但这里有一个选项:

      StreamBuilder(
                  stream: Firestore.instance
                      .collection("cars")
                      .snapshots(),
                  builder: (context, snapshot) {
                    if (!snapshot.hasData) {
                      return Center(child: CircularProgressIndicator());
                    } 
                    else {
                        print(snapshot.data.documents[0].documentID) //this prints the document id of the (0th) first element in the collection of cars
                     }
                    })
      

      您可以使用 listview-builder 来制作列表,在itemCount: 属性中,您可以使用snapshot.data.documents.lengthindex 通过以下方式访问所有元素的ID:snapshot.data.documents[index].documentID

      【讨论】:

        猜你喜欢
        • 2019-11-15
        • 2021-03-29
        • 2020-10-01
        • 2020-04-12
        • 2022-07-22
        • 2020-12-05
        • 2019-05-05
        • 1970-01-01
        • 2018-09-02
        相关资源
        最近更新 更多