How to properly wait until future is complete in dart

3,584

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.

Share:
3,584
mike-gallego
Author by

mike-gallego

Updated on December 09, 2022

Comments

  • mike-gallego
    mike-gallego over 1 year

    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.

    • anmol.majhail
      anmol.majhail about 5 years
      yes - use FutureBuider - for wait period - show loading element.