我想獲取共享首選項的 bool 來決定應該加載哪個 Widget,但是該方法不能是異步的或 bool 無法獲取該值,因為它不允許“等待”該值。我試過修復它,但它大多失敗了,因為“家”無法接收未來的小部件......,還有另一種方法可以做到這一點嗎?
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();
}
}
uj5u.com熱心網友回復:
您可以使用FutureBuilder上Home
Future<bool> checkifpassword() async {
//perfrom your async operation and return bool
return await Future.delayed(Duration(seconds: 2), () {
return true;
});
}
和 home
home: FutureBuilder<bool>(
future: checkifpassword(),
builder: (context, snapshot) {
if (snapshot.hasData) {
if (snapshot.data!) {// for true
return Login();;
} else return MyHomePage();
}
/// check others state
return Scaffold(
body: Center(
child: CircularProgressIndicator(),
),
);
},
)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/362195.html
上一篇:如何在顫振中實作滑動類別欄?
下一篇:tabBar的標題可以不居中嗎?
