使用SharedPreferences设置登录状态并在应用启动时进行检索-Flutter [英] Using SharedPreferences to set login state and retrieving it at App launch - Flutter
问题描述
我有一个Flutter应用程序,启动该应用程序时必须检查其登录状态,并相应地调用相关屏幕。
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));}
}
}
我是能够保存 SharedPreference
并在此处检索它,问题在于,由于 getLoginState()
是一个异步函数,<在执行if条件时,code> this.isLoggedIn 为null。布尔声明在if语句中失败,应用程序崩溃。
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.
如何确保布尔变量 isLoggedIn
任何帮助将不胜感激。
推荐答案
您可以使用 FutureBuilder 解决此问题。
You can use FutureBuilder to solve this problem.
@override
Widget build(BuildContext context) {
new FutureBuilder<String>(
future: getLoginState(),
builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.active:
case ConnectionState.waiting:
return new Text('Loading...');
case ConnectionState.done:
if (snapshot.hasData) {
loginState = snapshot.data;
if(loginState) {
return Container(child: Text('Logged In'));
}
else {
return Container(child: Text('Not Logged In));
}
} else {
return Container(child: Text('Error..));
}
}
},
)
}
注意:我们不需要 isLoggedIn
状态变量。
Note: we don't need isLoggedIn
state variable.
这篇关于使用SharedPreferences设置登录状态并在应用启动时进行检索-Flutter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!