Home > Mobile >  value of type 'bool?' can't be assigned to a variable of type 'bool'. Try c
value of type 'bool?' can't be assigned to a variable of type 'bool'. Try c

Time:12-13

//constants.dart   
static Future<bool?> getUserLoggedInDetails() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
return  prefs.getBool(isLoggedInKey);
}
//main.dart
checkUserLoggedInStatus() async {
Constants.getUserLoggedInDetails().then((value) {
setState(() {
_isLoggedIn =  value;//error is here
});
});
}

A value of type 'bool?' can't be assigned to a variable of type 'bool'. Try changing the type of the variable, or casting the right-hand type to 'bool'.

CodePudding user response:

Just give it a default value

static Future<bool> getUserLoggedInDetails() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  return  prefs.getBool(isLoggedInKey) ?? false;
}

main.dart

Future<void> checkUserLoggedInStatus() async {
  bool loggedIn = await Constants.getUserLoggedInDetails();
  setState(() {
    _isLoggedIn = loggedIn;
  });
}

CodePudding user response:

When you create your bool variable _isLoggedIn, make it nullable, cos 'value' might be null:

bool? isLoggedIn;

OR

_isLoggedIn =  value ?? false;
  • Related