Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

I have a Future function in my Provider Repository. However it is Future<bool> since I need async for http request.

Future<bool> hasCard() async {
    String token = await getToken();
    var body = jsonEncode({"token": token, "userID": user.getUserID()});
    var res = await http.post((baseUrl + "/hasCard"), body: body, headers: {
      "Accept": "application/json",
      "content-type": "application/json"
    print(res.toString());
    if (res.statusCode == 200) {
      this.paymentModel = PaymentModel.fromJson(json.decode(res.body));
      return true;
    return false;

And in my Widget I want to check this value:

Widget build(BuildContext context) {
    var user = Provider.of<UserRepository>(context);
    if(user.hasCard())
      //do something

But I get an error message:

Conditions must have a static type of 'bool'.dart(non_bool_condition)

Since it is a Widget type I cannot use async here. What could be the way to solve this?

You can use a FutureBuilder, it will build the widget according to the future value, which will be null until the future is completed. Here is an example.

FutureBuilder(
  future: hasCard(),
  builder: (context, snapshot) {
    if (snapshot.data == null)
      return Container(
          width: 20,
          height: 20,
          child: CircularProgressIndicator());
    if (snapshot.data)
      return Icon(
        Icons.check,
        color: Colors.green,
      return Icon(
        Icons.cancel,
        color: Colors.red,

Well not only for a Future<bool> for any other future you can use the FutureBuilder where the future is what returns you the type of future and snapshot is the data recieved from it.

  FutureBuilder(
      future: hasCard(),
      builder: (context, snapshot) {
        if (snapshot.data != null){
          print(snapshot.data)}
        else{
         print("returned data is null!")}  

and I would suggest assigning a default value to your bool.

good luck!

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.