Warm tip: This article is reproduced from stackoverflow.com, please click
dart flutter

How to get the result of a future within the builder method of a FutureBuilder widget?

发布于 2020-04-03 23:42:58

I have looked all over and cannot seem to find a solution to this problem. I have a Future<bool> = isAuth.

I have a future builder defined as follows:

FutureBuilder(
  future: isAuth,
  builder(context, snapshot){
    if(connectionState == connectionState.done){
      // Some Code Here
    }

    if(connectionState == ConnectionState.waiting){
      CircularProgressIndicator()
    }
  }

My question is, how do I return one widget if isAuth returns true, and another if isAuth returns false? I am displaying a loading spinner while waiting on the result of isAuth, and once I have the result, I want to display one of two forms?

Questioner
MarcElrick
Viewed
98
Augustin R 2020-01-31 21:00

You can access a FutureBuilder's future value with snapshot.data.

Don't forget to check if snapshot.data is defined using snapshot.hasData :

FutureBuilder<bool>(
  future: isAuth,
  builder: (context, snapshot) {
    if(connectionState == connectionState.done){
      if (snapshot.hasData){
        if (snapshot.data) return TrueWidget();
        else return FalseWidget();
        // Or with a one-liner :
        // return snapshot.data ? TrueWidget() : FalseWidget();
      }
    }

    if(connectionState == ConnectionState.waiting){
      return CircularProgressIndicator(); // Don't forget to return a widget in a builder method
    }
  }
)