Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter/Dart convert future bool to bool

Can some one help me to identify the issue in below piece of code

void main() async {
  bool c =getstatus();
  print(c);
  }

Future<bool> getMockData() {
  return Future.value(false);
}

bool getstatus() async   
{
  Future<bool> stringFuture = getMockData();
  bool message =  stringFuture;
  return(message); // will print one on console.

}
like image 712
Sandeep Ks Avatar asked Sep 03 '25 03:09

Sandeep Ks


2 Answers

To get values from a Future(async) method, you have to await them. And after await the variable you get is not a Future anymore. So basically your code should look like this:

void main() async {
  bool c = await getstatus();
  print(c);
}

Future<bool> getMockData() {
  return Future.value(false);
}

Future<bool> getstatus() async {
  bool message = await getMockData();
  return message;
}
like image 61
belinda.g.freitas Avatar answered Sep 05 '25 01:09

belinda.g.freitas


an async method must return Future of something then in the main you have to get the bool value by writing await

   void main() async {
      bool c = await getstatus();
      print(c); // will print false on the console.
    }
    
    Future<bool> getMockData() {
      return Future.value(false);
    }
    
    Future<bool> getstatus() async {
      bool stringFuture = await getMockData();
   
      return stringFuture; // will return false.
    }
like image 20
wafaa sisalem Avatar answered Sep 05 '25 01:09

wafaa sisalem