0

I have a checkLoginStatus() like this. It will be return true or false

checkLoginStatus() async {
    sharedPreferences = await SharedPreferences.getInstance();
    print(sharedPreferences.getString("token"));
    if (sharedPreferences.getString("token") != null) {
      return true;
    }
    return false;
  }

And I have a button A with the code below

press: () => {
if(checkLoginStatus()) {
      //..Some code
     } else {
      //..
     }
   }

I tap on button A and got

Another exception was thrown: type 'Future<dynamic>' is not a subtype of type 'bool'

Why ? And how can I check checkLoginStatus() return true or false in if() condition ?

Alex
  • 727
  • 1
  • 13
  • 32
  • Does this answer your question? [What is a Future and how do I use it?](https://stackoverflow.com/questions/63017280/what-is-a-future-and-how-do-i-use-it) – nvoigt Aug 25 '21 at 07:21

2 Answers2

1
  • Add return type to checkLoginStatus like
Future<bool> checkLoginStatus() async {
  //
}
  • Await for future to complete in if statement
() async => {
if(await checkLoginStatus()) {
  //
}

OR

Cast to Future<bool>

() async => {
if(await (checkLoginStatus() as Future<bool>)) {
  //
}
p2kr
  • 606
  • 6
  • 18
0

You have to await for checkLoginStatus() as Currently it has type of Future<dynamic>.

press: () => async {
final _checkLoginStatus = await checkLoginStatus();
if(_checkLoginStatus) {
      //..Some code
     } else {
      //..
     }
   }

Also, Do give a return type to your method.

Future<bool> checkLoginStatus() async {
    sharedPreferences = await SharedPreferences.getInstance();
    print(sharedPreferences.getString("token"));
    if (sharedPreferences.getString("token") != null) {
      return true;
    }
    return false;
  }
ibhavikmakwana
  • 8,948
  • 4
  • 20
  • 39