Flutter,如何使用多个共享偏好



我的目标是避免用户一旦关闭并重新打开应用程序就注销。因此,我使用shared_preferences在本地存储用户的电子邮件和密码,以便每当用户重新打开应用程序时,我可以使用firebase的signInWithEmailAndPassword并为其提供本地存储的电子邮件和密码。我使用setString()来存储电子邮件密码,但我只能存储电子邮件而不是密码,我得到错误"密码为空";我怎么解这个。我的代码写对了吗?

用户在app中注册时存储邮箱和密码

onPressed: () async {
try {
final user =
await _auth.createUserWithEmailAndPassword(
email: email, password: password);
if (user != null) {
final SharedPreferences sharedPreferences =
await SharedPreferences.getInstance();
sharedPreferences.setString(
'email',
email,
);
sharedPreferences.setString('password', password);
Get.to(() => const BorrowerList());
}
} catch (e) {
Get.snackbar('Error', e.toString(),
backgroundColor: (Colors.red));
}
},

重新打开后获取邮箱密码和登录。

@override
void initState() {
super.initState();
validateUserAuth();
}
final _firestore = FirebaseFirestore.instance;
void validateUserAuth() async {
final SharedPreferences sharedPreferences =
await SharedPreferences.getInstance();
var obtainedEmail = sharedPreferences.getString('email');
var obtainedPassword = sharedPreferences.getString('password');
if (obtainedEmail != null || obtainedPassword != null) {
setState(() {
loggedinUserEmail = obtainedEmail!;
loggedinUserPassword = obtainedPassword!;
});
if (loggedinUserEmail != null || loggedinUserPassword != null) {
final loggedinuser = await auth.signInWithEmailAndPassword(
email: loggedinUserEmail, password: obtainedPassword!);
if (loggedinuser != null) {
Get.to(() => const BorrowerList());
}
}
} else {
Get.to(() => AuthScreen());
}
}

错误很明显。shared_preferences中不能保存null

您的代码不完整。你的password变量是null

你可以粘贴完整的代码,这样我们可以更好地帮助你

你能提供更多关于这个项目的信息吗?到目前为止,很明显您正在尝试在shared_preferences中存储空值。你不能这么做。我很确定问题是当用户输入密码时,它不会存储在这里的password变量中:

try {
final user =
await _auth.createUserWithEmailAndPassword(
email: email, password: password);
if (user != null) {
final SharedPreferences sharedPreferences =
await SharedPreferences.getInstance();
sharedPreferences.setString(
'email',
email,
);
// NULLABLE VARIABLE!
sharedPreferences.setString('password', password);
Get.to(() => const BorrowerList());
}
} catch (e) {
Get.snackbar('Error', e.toString(),
backgroundColor: (Colors.red));
}
},

另外,不建议使用shared_preferences来存储敏感数据。颤振安全存储更适合于此。

最新更新