Search code examples
asynchronousdartflutterdart-async

How to finish the async Future task before executing the next instruction Flutter


I make a function call to my database, which updates a local object after getting data and takes a few moments.

Because of the Async task, the program moves to the next line of code. unfortunately I need the local object that gets updated with the async call for the next line of code.

how can I wait for my async task to finish before the next piece of code is executed? thank you

edit: adding code to explain

updateUser() {
return FutureBuilder(
        future: updateUserData(),
        builder: (BuildContext context, AsyncSnapshot snapshot) {
          if (snapshot.connectionState != ConnectionState.done) {
            return Text("hello not");
          } else {
            return Text('Hello!');
          }
        },

);}

  @override
  Widget build(BuildContext context) {
    switch (_authStatus) {
      case AuthStatus.notSignedIn:
        return new LoginPage(
          auth: auth,
          CurrentUser: CurrentUser,
          onSignedIn: _signedIn,
        );
      case AuthStatus.signedIn:
        {
          updateUser(); //THIS TAKES A COUPLE SECONDS TO FINISH BUT I NEED TO SEND IT TO THE NEXT PAGE

            return new HomePage(
              auth: auth,
              CurrentUser: CurrentUser,
              onSignedOut: _signedOut,
            );
          }
        }
    }
  }

Solution

  • You can use await keyword in async function.

    eg:

      void someFunc() async {
        await someFutureFunction();
        // Your block of code
      }
    

    Here your block of code wont run until someFutureFunction returns something.