Thoxh
Thoxh

Reputation: 149

Returning int in a function with Future, async, await to add at Firestore - Flutter

I'm trying to return a int in this function:

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

and now I want to use it right here in a onTap-methode of my GestureDetector:

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

However, if I tap my button the application crashs and it showed me following in VS Code:

Error

I think the problem is connected to the Future, async and await. I also tried to set an await before getID() but for that a async is also needed but I dont know where to include it in my Stateful class if its the right way.

Thanks for you help.

Upvotes: 0

Views: 120

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 599041

This won't work:

"id": getID(),

Since getID returns a Future<int>, you're trying to set a Future to thd database, and that is not a supported type.

This should work:

"id": await getID(),

As now you are waiting for the Future to be resolved.

Upvotes: 2

Related Questions