【问题标题】:Flutter and Firestore: How can I get the document Id from the add function?Flutter 和 Firestore:如何从 add 函数中获取文档 ID?
【发布时间】:2021-03-12 15:24:35
【问题描述】:

我向 Firestore 添加了一个文档。如何获取我添加的文档的文档 ID?我想把它保存到一个变量中。

顺便说一句。如果这很重要,我会将其用于网络应用程序。

FirebaseFirestore.instance.collection('room').add({
    'name': _name,
    'points': 0,
});

【问题讨论】:

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


    【解决方案1】:

    这样做

    User user = FirebaseAuth.instance.currentUser;
    
    FirebaseFirestore.instance.collection('room').add({
        'id': user.uid,
        'name': _name,
        'points': 0,
    });
    

    【讨论】:

      【解决方案2】:

      在末尾添加.then方法。

      使用 docRef 做任何你需要的事情。

      FirebaseFirestore.instance.collection('room').add({
          'name': _name,
          'points': 0,
      }).then(function(docRef) {
          console.log("Document written with ID: ", docRef.id);
      })
      
      

      【讨论】:

        【解决方案3】:

        CollectionReference 上的 add 方法返回 Future<DocumentReference>。 [Documentation]

        Future<DocumentReference> add(Map<String, dynamic> data) async {
          final DocumentReference newDocument = doc();
          await newDocument.set(data);
          return newDocument;
        }
        

        那么,试试这个:

        FirebaseFirestore.instance.collection('room')
          .add({
            'name': _name,
            'points': 0,
          })
          .then((docRef) => print(docRef.id));
        

        【讨论】:

          【解决方案4】:

          调用CollectionReference.add会返回Future&lt;DocumentReference&gt;,因此您可以从中获取ID:

          var newDocRef = await FirebaseFirestore.instance.collection('room').add({
              'name': _name,
              'points': 0,
          })
          var newDocId = newDocRef.id
          

          如果你想将ID存储在文档中,最好先通过不带参数调用CollectionReference.doc()来创建DocumentReference

          var newDocRef = FirebaseFirestore.instance.collection('room').doc();
          var newDocId = newDocRef.id
          newDocRef.set({
              'id': newDocId,
              'name': _name,
              'points': 0,
          })
          

          【讨论】:

            猜你喜欢
            • 2020-12-05
            • 2019-05-05
            • 2021-07-20
            • 2021-12-16
            • 2022-07-22
            • 2021-01-05
            • 1970-01-01
            • 1970-01-01
            • 2019-08-02
            相关资源
            最近更新 更多