【发布时间】:2021-11-21 02:33:45
【问题描述】:
我想获取共享首选项的布尔值来决定应该加载哪个小部件,但是该方法不能是异步的或布尔值不能获取值,因为它不允许“等待”该值。我已经尝试修复它,但它大多失败,因为“家”无法接收未来的小部件......,还有其他方法可以做到这一点吗?
void main() => runApp(MyApp());
setloginbool() async{
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setBool("savelogin", true);
}
Future<bool> getloginbool() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
bool savelogin = prefs.getBool("savelogin") ?? false;
return savelogin;
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'KHS Plan',
theme: (ThemeData(
textTheme: const TextTheme(
bodyText1: TextStyle(fontSize: 14)
)
)),
home: checkifpassword(),
);
}
}
Widget checkifpassword() {
bool s = await getloginbool();
if(s){
return const Login();
} else {
return const MyHomePage();
}
}
//This does not work as well
checkifpassword() async {
bool s = await getloginbool();
if(s){
return const Login();
} else {
return const MyHomePage();
}
}
【问题讨论】:
-
好的,您想从
checkifpassword()加载home上的小部件? -
是的,我也想用 bool 来决定加载哪个
标签: flutter asynchronous async-await sharedpreferences