I have an flutter app in which I have to check the login status when the app is launched and call the relevant screen accordingly.
The code used to launch the app:
class MyApp extends StatefulWidget {
@override
MyAppState createState() {
return new MyAppState();
}
}
class MyAppState extends State<MyApp> {
bool isLoggedIn;
Future<bool> getLoginState() async{
SharedPreferences pf = await SharedPreferences.getInstance();
bool loginState = pf.getBool('loginState');
return loginState;
// return pf.commit();
}
@override
Widget build(BuildContext context) {
getLoginState().then((isAuth){
this.isLoggedIn = isAuth;
});
if(this.isLoggedIn) {return Container(child: Text('Logged In'));}
else {return Container(child: Text('Not Logged In));}
}
}
I am able to save the SharedPreference
and retrieve it here, the issue is that as getLoginState()
is an async function, this.isLoggedIn
is null by the time the if condition is executed. The boolean assertion fails in the if statement and the app crashes.
How do I ensure that the bool variable isLoggedIn
used in the if condition has a value when the if statement is executed?
Any help would be appreciated.