【问题标题】:Returning int in a function with Future, async, await to add at Firestore - Flutter在具有 Future、异步、等待在 Firestore 添加的函数中返回 int - Flutter
【发布时间】:2021-10-16 00:18:49
【问题描述】:

我试图在这个函数中返回一个 int:

  Future<int> getID() async {
    DocumentSnapshot idSnapshot = await FirebaseFirestore.instance
        .collection("Bestellungen")
        .doc("default")
        .get();
    int currentID = idSnapshot["id"] + 1;
    return await currentID;
  }

现在我想在我的 GestureDetector 的 onTap 方法中使用它:

onTap: () {
                                Scaffold.of(context).hideCurrentSnackBar();
                                FirebaseFirestore.instance
                                    .collection("Bestellungen")
                                    .add({
                                  "id": getID(),
                                  "item": document["titel"],
                                  "done": false,
                                  "time": getTime(),
                                });
                              }

但是,如果我点击我的按钮,应用程序会崩溃,并在 VS Code 中显示以下内容:

我认为问题与 Future、async 和 await 相关。 我还尝试在 getID() 之前设置等待,但为此还需要异步,但如果方法正确,我不知道将它包含在我的 Stateful 类中的哪个位置。

感谢您的帮助。

【问题讨论】:

  • 您能向我们展示您获得的确切错误消息和完整的堆栈跟踪,而不是向我们展示调试器的屏幕截图吗?

标签: flutter google-cloud-firestore async-await


【解决方案1】:

这行不通:

"id": getID(),

由于getID 返回Future&lt;int&gt;,您正尝试将Future 设置为thd 数据库,这不是受支持的类型。

这应该可行:

"id": await getID(),

现在您正在等待Future 得到解决。

【讨论】:

  • 也试过了,但我需要在代码中的某处添加异步,将其添加到数据库中。你知道在哪里吗?
  • flutter.institute/run-async-operation-on-widget-creation 我找到了那个。我认为这应该是解决方案。我会在几分钟内尝试。
  • @Thoxh 或使用FutureBuilder
  • 由于这里唯一使用异步getID() 是在onTap 内并且不返回小部件,所以我不确定如何使用FutureBuilder。但如果这确实是可能的,我很乐意看到你展示如何做的答案。 ?
猜你喜欢
  • 1970-01-01
  • 2020-05-06
  • 2013-07-24
  • 2019-01-25
  • 1970-01-01
  • 2019-08-03
  • 2011-03-04
  • 2020-08-19
  • 2020-07-14
相关资源
最近更新 更多