How to properly wait until future is complete in dart
Asked Answered
E

1

1

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.

Evette answered 11/2, 2019 at 15:58 Comment(1)
yes - use FutureBuider - for wait period - show loading element.Silken
L
7

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.

Leavening answered 11/2, 2019 at 16:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.