【问题标题】:How to call a function only once in a for loop of 'Firestore DocumentSnapshot'? [duplicate]如何在'Firestore DocumentSnapshot'的for循环中只调用一次函数? [复制]
【发布时间】:2021-04-07 00:50:41
【问题描述】:

我正在尝试从 firestore 删除文档,使用:

 FirebaseFirestore.instance
      .collection("Data")
      .where('user_id', isEqualTo: uid)
      .get()
      .then((snapshot) {
    for (DocumentSnapshot ds in snapshot.docs) {
      ds.reference.delete().then((value) {
        print("document deleted");
        moveToNextDeletion(); // <-The function shold be called only once
      });
    }
  });

所以一旦所有文档被删除,我想调用moveToNextDeletion(); 函数,但它会一直调用直到所有文档被删除(导致 for 循环)。

删除所有文档后,有什么方法可以调用该函数吗?

【问题讨论】:

  • 您需要将每次调用 delete() 返回的所有期货收集到一个数组中,并使用 Future.wait 等待它们。
  • 调用delete()时firebase不会返回任何东西,所以我没有任何东西可以收集到数组中!
  • 不,delete() 返回一个 Future。您的代码当前正在调用 then() 一个。
  • 谢谢,@dougStevenson 你的评论很有用。

标签: firebase flutter dart google-cloud-firestore


【解决方案1】:

使用while循环而不是for循环希望它能起作用

【讨论】:

    【解决方案2】:

    使用 .whenCompleted() 代替此方法在您指定的操作完成时触发,而不是使用 then。

    Difference between .then() and .whenCompleted() methods when working with Futures?

    据我所知,.then() 函数返回前一个函数的工作结果。在这里,您正在执行删除操作。所以你没有从数据库中得到任何结果。

     FirebaseFirestore.instance
          .collection("Data")
          .where('user_id', isEqualTo: uid)
          .get()
          .then((snapshot) {
        for (DocumentSnapshot ds in snapshot.docs) {
          ds.reference.delete().then((value) {
            print("document deleted");
            
          });
        }
      }).whenCompleted(() {
        moveToNextDeletion(); // <-The function shold be called only once
      });
    

    我想这会解决你的问题。如果它解决了问题然后ping我我会解释

    【讨论】:

    • 即使我使用 whenCompleted() 它仍然在 for 循环内,因此下一个函数将继续发生,直到 for 循环完成。
    • 您能否准确解释一下您想要做什么,因为您似乎想删除数据库中的一个特定文档ds.reference.delete(),而这一行说明了一些不同的内容。我想您应该将检索到的值传递给您的参考 ds.collection('data').doc(ds.id).delete() 类似这样的东西
    • 我想删除 QuerySnapshot 中的每个文档,所以我调用了一个 for 循环来“逐个读取每个文档以删除该文档的引用”,问题是' t 删除!,一旦所有引用被删除,我想调用另一个函数
    • ``` FirebaseFirestore.instance .collection("Data") .where('user_id', isEqualTo: uid) .get() .then((snapshot) { for (DocumentSnapshot ds in snapshot. docs) { ds.reference.delete().then((value) { print("document deleted"); }); } }).whenCompleted(() {moveToNextDeletion(); //
    • 谢谢,我有另一个解决方案。感谢您的帮助:)
    猜你喜欢
    • 2014-07-25
    • 1970-01-01
    • 1970-01-01
    • 2013-05-06
    • 2015-05-29
    • 1970-01-01
    • 2016-01-09
    • 1970-01-01
    相关资源
    最近更新 更多