Alex
Alex

Reputation: 827

'Future<dynamic>' is not a subtype of type 'bool'

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 ?

Upvotes: 0

Views: 1254

Answers (2)

ibhavikmakwana
ibhavikmakwana

Reputation: 10101

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;
  }

Upvotes: 0

p2kr
p2kr

Reputation: 604

  • 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>)) {
  //
}

Upvotes: 1

Related Questions