Home > OS >  Flutter/Dart convert future bool to bool
Flutter/Dart convert future bool to bool

Time:04-28

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.

}

CodePudding user response:

Future<bool> stringFuture = await getMockData();

CodePudding user response:

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 {
      Future<bool> stringFuture = await getMockData();
   
      return stringFuture; // will return false.
    }

CodePudding user response:

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 = getstatus();
  print(c);
}

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

bool getstatus() async {
  bool stringFuture = await getMockData();
  bool message = stringFuture;
  return(message);
}
  • Related