【问题标题】:how can i retrieve document id of each document from Firestore in flutter如何在颤动中从 Firestore 中检索每个文档的文档 ID
【发布时间】:2020-11-08 01:28:18
【问题描述】:

这里我有从 Firebase 检索所有文档的代码,我只能检索文档中存在的数据,但我也想用它检索文档 ID,我该怎么做?

StreamBuilder<QuerySnapshot>(
          stream: getData(),
          builder: (BuildContext context,
              AsyncSnapshot<QuerySnapshot> snapshot) {
            if (snapshot.hasError)
              return new Text('Error: ${snapshot.error}');
            switch (snapshot.connectionState) {
              case ConnectionState.waiting:
                return new Text('Loading...');
              default:
                return new ListView(
                  children: snapshot.data.documents
                      .map((DocumentSnapshot document) {
                    return new CustomCard(
                      name: document['name'],
                      phone: document['phno'],
                      service: document['Category'],
                      address: document['address'],
                      pin: document['pin'],
                      payment: document['Payment'],
                    );
                  }).toList(),
                );
            }
          },
        ),

这是我的getter函数

     Stream<QuerySnapshot> getData()async*{
    FirebaseUser user = await FirebaseAuth.instance.currentUser();
    yield* Firestore.instance
        .collection('User')
        .where("userId", isEqualTo: user.uid)
        .orderBy('upload time', descending: true)
        .snapshots();
  }

【问题讨论】:

    标签: firebase flutter dart google-cloud-firestore flutter-dependencies


    【解决方案1】:

    要获取 id,请执行以下操作:

     .map((DocumentSnapshot document) {
                        return new CustomCard(
                          docId : document.documentID,
                          name: document['name'],
                          phone: document['phno'],
                          service: document['Category'],
                          address: document['address'],
                          pin: document['pin'],
                          payment: document['Payment'],
                        );
                      }).toList(),
    

    documentID 会给你每个文档的 ID。

    【讨论】:

      【解决方案2】:

      你也可以这样做

      snapshot.data!.docs[index].id
      

      这将返回该索引处文档的 id

      【讨论】:

      • 工作就像一个魅力!为我节省了很多时间。谢谢
      • 也为我工作
      猜你喜欢
      • 2021-04-14
      • 2021-11-11
      • 1970-01-01
      • 2018-05-13
      • 2020-08-05
      • 1970-01-01
      • 2020-12-05
      • 1970-01-01
      相关资源
      最近更新 更多