mike-gallego
mike-gallego

Reputation: 724

How to properly wait until future is complete in dart

There is a slight bug in my app made with Flutter, that when the user has signed in, it fetches the user information from my database but not fast enough and causes a visual error on my front end of the app. The app has layouts that use the user information (name, location, and image) and it is not being loaded quick enough. I was wondering if there is a way to wait for my future to complete and once it is done, it can navigate the user to the front end with no problem.

Upvotes: 1

Views: 4010

Answers (1)

Mazin Ibrahim
Mazin Ibrahim

Reputation: 7869

You Should fetch your date from the database in the initState() function, then you have to modify your widget builder to use FutureBuilder, here's an example:

Widget build(BuildContext context) {
return FutureBuilder(
    future: getProfile(),
    builder: (BuildContext context, AsyncSnapshot<SharedPreferences> snapshot) {
      if(snapshot.connectionState == ConnectionState.done){
        return new MaterialApp();
      }
    }
  )
}

note that you can replace AsyncSnapshot<SharedPreferences> with the type your Future function returns.

Upvotes: 7

Related Questions