【问题标题】:How do I get documentid of a firestore document in flutter?如何在flutter中获取firestore文档的documentid?
【发布时间】:2020-11-08 02:48:06
【问题描述】:

我尝试了以下方法,但它返回了一个随机字符串,该字符串不存在于 firestore 中。

我确实设法使用查询快照获取父集合的 documentid

DocumentReference doc_ref=Firestore.instance.collection("board").document(doc_id).collection("Dates").document();

                    var doc_id2=doc_ref.documentID;

更多代码:我在尝试访问文档 ID 时遇到错误。我曾尝试使用 await,但它给出了错误。

 Widget build(BuildContext context) {
        return Scaffold(
          appBar: new AppBar(
            title: new Text(
              "National Security Agency",
              style: TextStyle(
                  color: Colors.black,
                  fontWeight: FontWeight.normal,
                  fontSize: 24.0),
            ),
            backgroundColor: Colors.redAccent,
            centerTitle: true,
            actions: <Widget>[
              new DropdownButton<String>(
                items: <String>['Sign Out'].map((String value) {
                  return new DropdownMenuItem<String>(
                    value: value,
                    child: new Text(value),
                  );
                }).toList(),
                onChanged: (_) => logout(),
              )
            ],
          ),
          floatingActionButton: FloatingActionButton(
            onPressed: () {
    
            },
            child: Icon(Icons.search),
          ),
    
          body: StreamBuilder (
              stream: cloudfirestoredb,
    
    
                  builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
                    if (!snapshot.hasData) return new Text('Loading...');
    
                    return new ListView(
                      children: snapshot.data.documents.map((document) {
    
    
                        var doc_id=document.documentID;
                        var now= new DateTime.now();
                        var formatter=new DateFormat('MM/dd/yyyy');
                        String formatdate = formatter.format(now);
                        var date_to_be_added=[formatdate];
    
                        DocumentReference doc_ref=Firestore.instance.collection("board").document(doc_id).collection("Dates").document();
    
                       var doc_id5= await get_data(doc_ref);
    
    
                        print(doc_id);
                        
    
    
                        Firestore.instance.collection("board").document(doc_id).collection("Dates").document(doc_id5).updateData({"Date":FieldValue.arrayUnion(date_to_be_added)});
                        return cardtemplate(document['Name'], document['Nationality'], doc_id);
    
                        }).toList(),
                    );
                  },
           ),
              );
      }

【问题讨论】:

    标签: firebase flutter dart google-cloud-firestore


    【解决方案1】:

    更新后,现在可以使用这行代码来访问doc id,

    snapshot.data.docs[index].reference.id
    

    其中快照是一个查询快照。

    这是一个例子。

    FutureBuilder(
        future: FirebaseFirestore.instance
            .collection('users')
            .doc(FirebaseAuth.instance.currentUser!.uid)
            .collection('addresses')
            .get(),
        builder: (context, AsyncSnapshot snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            return Center(child: CircularProgressIndicator());
          }else{return Text(snapshot.data.docs[0].reference.id.toString());}
    

    【讨论】:

    • 最简单的解决方案
    【解决方案2】:
    • 要获取集合中的文档 ID:

      var collection = FirebaseFirestore.instance.collection('collection');
      var querySnapshots = await collection.get();
      for (var snapshot in querySnapshots.docs) {
        var documentID = snapshot.id; // <-- Document ID
      }
      
    • 获取新添加数据的文档ID:

      var collection = FirebaseFirestore.instance.collection('collection');
      var docRef = await collection.add(someData);
      var documentId = docRef.id; // <-- Document ID
      

    【讨论】:

      【解决方案3】:

      您可以通过以下方式在文档中添加值后使用value.id获取documentId:-

      CollectionReference users = FirebaseFirestore.instance.collection('candidates');
        
        Future<void> registerUser() {
       // Call the user's CollectionReference to add a new user
           return users.add({
            'name': enteredTextName, // John Doe
            'email': enteredTextEmail, // Stokes and Sons
            'profile': dropdownValue ,//
            'date': selectedDate.toLocal().toString() ,//// 42
          })
              .then((value) =>(showDialogNew(value.id)))
              .catchError((error) => print("Failed to add user: $error"));
        }
      

      这里value.id给出了ducumentId。

      【讨论】:

        【解决方案4】:

        您还可以执行以下操作

        Firestore.instance
            .collection('driverListedRides')
            .where("status", isEqualTo: "active")
            .getDocuments()
            .then(
              (QuerySnapshot snapshot) => {
                driverPolylineCordinates.clear(),
                snapshot.documents.forEach((f) {
                
                  print("documentID---- " + f.reference.documentID);
                 
                }),
              },
            );
        

        【讨论】:

          【解决方案5】:

          您必须检索该文档的 ID。

          试试这个

          
          DocumentReference doc_ref=Firestore.instance.collection("board").document(doc_id).collection("Dates").document();
          
                              DocumentSnapshot docSnap = await doc_ref.get();
                               var doc_id2 = docSnap.reference.documentID;
          
          

          确保在标记为 async 的函数中使用它,因为代码使用 await。

          编辑: 在 cmets 中回答您的问题

          Future<String> get_data(DocumentReference doc_ref) async { 
          DocumentSnapshot docSnap = await doc_ref.get(); 
          var doc_id2 = docSnap.reference.documentID; 
          return doc_id2; 
          }
          
          //To retrieve the string
          String documentID = await get_data();
          

          编辑 2:

          只需将异步添加到地图功能。

          snapshot.data.documents.map((document) async {
              
              
                                  var doc_id=document.documentID;
                                  var now= new DateTime.now();
                                  var formatter=new DateFormat('MM/dd/yyyy');
                                  String formatdate = formatter.format(now);
                                  var date_to_be_added=[formatdate];
              
                                  DocumentReference doc_ref=Firestore.instance.collection("board").document(doc_id).collection("Dates").document();
              
                                 var doc_id5= await get_data(doc_ref);
              
              
                                  print(doc_id);
                                  
              
              
                                  Firestore.instance.collection("board").document(doc_id).collection("Dates").document(doc_id5).updateData({"Date":FieldValue.arrayUnion(date_to_be_added)});
                                  return cardtemplate(document['Name'], document['Nationality'], doc_id);
              
                                  }).toList(),
          

          让我知道这是否有效

          【讨论】:

          • 我添加了以下功能。但是我怎样才能从 Future String Instance Future get_data(DocumentReference doc_ref) async{ DocumentSnapshot docSnap = await doc_ref.get(); var doc_id2 = docSnap.reference.documentID;返回 doc_id2; }
          • 谢谢。但是我在使用 await 时遇到了错误。可能是因为我没有使用 Future Builder。我正在使用 Stream Builder 并返回一个列表视图。我该如何解决这个问题?
          • 检查一次
          • 感谢您的宝贵时间。我尝试了另一种方法,使用另一个函数并在开始时对其进行初始化。有效。感谢您帮助我
          • 欢迎您,随时!如果您真的认为此答案对您有所帮助,您能否将其标记为已回答? (绿色勾号)。堆栈溢出奖励基于此的声誉,这有助于我回答其他人。谢谢!
          【解决方案6】:

          document()当你在没有任何路径的情况下调用这个方法时,它会为你创建一个随机的id。

          来自文档:

          如果未提供 [path],则使用自动生成的 ID。 生成的唯一键以客户端生成的时间戳为前缀 这样生成的列表将按时间顺序排序。

          因此,如果您想获取documentID,请执行以下操作:

          var doc_ref = await Firestore.instance.collection("board").document(doc_id).collection("Dates").getDocuments();
          doc_ref.documents.forEach((result) {
            print(result.documentID);
          });
          

          【讨论】:

          • 谢谢。我试图在异步函数中实现它,但在尝试返回它时收到错误。我试图使用“等待”......但没有帮助。请查看我在问题中添加的代码
          • 这对我有用,但我可以在 listview builder 中列出它们
          猜你喜欢
          • 2021-01-08
          • 1970-01-01
          • 2019-05-05
          • 2020-12-05
          • 2019-10-03
          • 2019-04-20
          • 2022-07-22
          • 2021-07-20
          • 2019-04-14
          相关资源
          最近更新 更多