Dart 使用SharedReferences设置登录状态并在应用程序启动时检索它-颤振
我有一个Flitter应用程序,我必须在应用程序启动时检查登录状态,并相应地调用相关屏幕 用于启动应用程序的代码:Dart 使用SharedReferences设置登录状态并在应用程序启动时检索它-颤振,dart,flutter,Dart,Flutter,我有一个Flitter应用程序,我必须在应用程序启动时检查登录状态,并相应地调用相关屏幕 用于启动应用程序的代码: class MyApp extends StatefulWidget { @override MyAppState createState() { return new MyAppState(); } } class MyAppState extends State<MyApp> { bool isLoggedIn; Future&l
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));}
}
}
我可以保存SharedReference并在这里检索它,问题是由于getLoginState是一个异步函数,因此在执行if条件时this.isLoggedIn为null。if语句中的布尔断言失败,应用程序崩溃
在执行if语句时,如何确保if条件中使用的bool变量isLoggedIn具有值
任何帮助都将不胜感激。您可以用它来解决此问题
@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状态变量。您可以使用它来解决此问题
@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状态变量