Does anyone know why i got the Failed assertion: boolean expression must not be null. If I had logged in and quit the app and open the app again i should be directly in the home
Your issue most likely lies in this function where you're setting userIsLoggedIn to null. Ensure getUserLoggedInSharedPreference actually returns a boolean and not null.
void getLoggedInState() async {
final result = await HelperFunction.getUserLoggedInSharedPreference();
if (result != null) {
setState(() {
userIsLoggedIn = result;
});
} else {
print("result is null");
}
}
If your 'value' here can become null - you get the error. To be safe change the line inside setState to:
userIsLoggedIn = value ?? false;
it will set the bool to false if value is null
Your problem is that you are not waiting for your Future to resolve to an actual value.
This line:
userIsLoggedIn = value;
might not have been reached when your build method is called. Because it's async and you don't await it.
You can set a default value to userIsLoggedIn, maybe false, that will solve your immediate problem. But it will not solve your real problem, that your program logic is asynchronous.
You will probably want to build your app with at least one FutureBuilder.
See: What is a Future and how do I use it?
You have a global approach error. You combine traditional and async/await methods in this code:
getLoggedInState()async{
await HelperFunction.getUserLoggedInSharedPreference().then((value){
setState(() {
userIsLoggedIn = value;
});
});
}
If you use async/await you should not use then method.
To implement what you want you should use something like this:
...
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: FutureBuilder<bool>(
future: HelperFunction.getUserLoggedInSharedPreference(),
builder: (context,snapshot) {
if (snapshot.hasData) {
// Future is ready. Take data from snapshot
userIsLoggedIn = snapshot.data; // bool value is here
return userIsLoggedIn ? HomeScreen() : CompanyLoadingBar();
} else {
// Show progress while future will be completed
return CircularProgressIndicator();
}
}
),
);
}
...
And also check what value is returned from HelperFunction.getUserLoggedInSharedPreference(). It seems it returns null because I think you have no already saved value. So you need to specify the default value:
final value = await SharedPreferences.getInstance().readBool(name) ?? false;