我最初遵循的是在这里找到的答案代码:
我把它合并到pub.dev上的pub.dev包中
我成功地让它在第一次加载时为我的入职页面加载页面。然后,当我完成入职页面时,我尝试将共享首选项值设置为“true”,所以当我重新加载应用程序时,它将跳过入职页面,但当我在VS代码中的模拟器中测试时,它不起作用。
我在这里检查第一本书的价值:
class _MyAppState extends State<MyApp> {
bool isLoggedIn = false;
_MyAppState() {
MySharedPreferences.instance
.getBooleanValue("isfirstRun")
.then((value) => setState(() {
isLoggedIn = value;
}));
}如果错误,我会在这里加载入职屏幕:
home: isLoggedIn ? MainPage() : OnBoard(),我共享的Pref文件是:
导入'package:shared_preferences/shared_preferences.dart';
class MySharedPreferences {
MySharedPreferences._privateConstructor();
static final MySharedPreferences instance =
MySharedPreferences._privateConstructor();
setBooleanValue(String key, bool value) async {
SharedPreferences myPrefs = await SharedPreferences.getInstance();
myPrefs.setBool(key, value);
}
Future<bool> getBooleanValue(String key) async {
SharedPreferences myPrefs = await SharedPreferences.getInstance();
return myPrefs.getBool(key) ?? false;
}
}当入职板完成后,我运行以下命令:
MySharedPreferences.instance.setBooleanValue("loggedin", true);
//replace with main page
Route route = MaterialPageRoute(builder: (context) => MainPage());
Navigator.pushReplacement(context, route);如果我热重新加载VS一切都是好的,但如果我重新启动应用程序,它运行的入职屏幕每次。
发布于 2022-04-13 13:52:30
您应该检查并更改initstate函数中的isLoggedIn值。
例如
class _MyAppState extends State<MyApp> {
bool isLoggedIn = false;
@override
void initState() {
MySharedPreferences.instance
.getBooleanValue("isfirstRun")
.then((value) => setState(() {
isLoggedIn = value;
}));
super.initState();
}
@override
Widget build(BuildContext context) {
return Something...
}发布于 2022-04-13 14:36:28
在单独的函数中使用async和await,然后在initState中使用
void verityFirstRun() async {
final verification = await SharedPreferences.getInstance();
isLoggedIn = verification.getBool("isfirstRun") ?? false;
}
@override
void initState() {
verityFirstRun();
super.initState();
}使用这种方式调用SharedPreferences实例:
final verification = await SharedPreferences.getInstance();https://stackoverflow.com/questions/71858407
复制相似问题