如何使用共享首选项让用户保持登录状态
How to use shared prefs for keeping user logged in flutter
我为使用 firebase 身份验证的 flutter 应用程序创建了一个登录页面。有人可以帮助我在此使用共享首选项,以便用户即使终止应用程序也能保持登录状态
好吧,在你的登录函数中,如果验证成功,你应该将数据保存在 sharePreference 中;
/// your statefull code
void login() {
// get the inputValues;
// if validation success do this
this._persistUserInfo();
}
void _persistUserInfo() async {
final sharePrefsInstance = await SharedPreferences.getInstance();
sharePrefsInstance .setString("email", EMAIL_VALUE);
sharePrefsInstance .setString("password", _PASSWORD_VALUE);
}
/// your other statefull code;
上面的代码会将信息保存在设备上;
要检索其中的数据,请在 LoginScreen 的 initState 中执行此操作
@override
void initState() {
super.initState();
Future.delayed(
Duration(seconds: 3),
() async {
final sharePrefsInstance = await SharedPreferences.getInstance();
final email = sharePrefsInstance.getString("email");
final password = sharePrefsInstance.getString("password");
if( email != null && password != null) {
// navigate to your other screen since the user is authenticated
}
},
);
}
我为使用 firebase 身份验证的 flutter 应用程序创建了一个登录页面。有人可以帮助我在此使用共享首选项,以便用户即使终止应用程序也能保持登录状态
好吧,在你的登录函数中,如果验证成功,你应该将数据保存在 sharePreference 中;
/// your statefull code
void login() {
// get the inputValues;
// if validation success do this
this._persistUserInfo();
}
void _persistUserInfo() async {
final sharePrefsInstance = await SharedPreferences.getInstance();
sharePrefsInstance .setString("email", EMAIL_VALUE);
sharePrefsInstance .setString("password", _PASSWORD_VALUE);
}
/// your other statefull code;
上面的代码会将信息保存在设备上;
要检索其中的数据,请在 LoginScreen 的 initState 中执行此操作
@override
void initState() {
super.initState();
Future.delayed(
Duration(seconds: 3),
() async {
final sharePrefsInstance = await SharedPreferences.getInstance();
final email = sharePrefsInstance.getString("email");
final password = sharePrefsInstance.getString("password");
if( email != null && password != null) {
// navigate to your other screen since the user is authenticated
}
},
);
}