无论如何要在flutter中使用sharedPreferences启用“记住我"功能? [英] Anyway to enable 'remember me' function using sharedPreferences in flutter?
问题描述
当前,如果用户成功登录一次,我将启用保持登录"功能.但是,我仍然要选中记住我"复选框,以为用户保存成功登录信息.谁能帮我这个忙吗?
Currently, I have enabled 'keep logging in' function if the user log in once successfully. However, I still want to make a 'remember me' checkbox to save the success login information for user. Can anyone please help me with this?
需要:一个复选框,如果用户成功登录一次,该复选框使用户能够存储电子邮件和密码.
Need: a checkbox that enables the user to store email and password if the user logged in once successfully.
代码如下所示:
signIn(String email, pass) async {
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
String url = ServerDetails.ip +
':' +
ServerDetails.port +
ServerDetails.api +
'login';
Map<String, String> headers = {"Content-type": "application/json"};
var data = jsonEncode({
'email': email,
'password': pass,
'token': FirebaseNotifications.fcmtoken
});
var jsonResponse = null;
var response = await http.post(url, headers: headers, body: data);
if (response.statusCode == 200) {
jsonResponse = json.decode(response.body);
if (jsonResponse != null) {
setState(() {
_isLoading = false;
});
sharedPreferences.setString("token", jsonResponse['token']);
sharedPreferences.setString(
"token_expire_date", jsonResponse['token_expire_date']);
Navigator.of(context).pushAndRemoveUntil(
MaterialPageRoute(builder: (BuildContext context) => MainPage()),
(Route<dynamic> route) => false);
}
} else {
setState(() {
_isLoading = false;
});
Widget okButton = FlatButton(
child: Text("OK"),
onPressed: () {
Navigator.push(
context, MaterialPageRoute(builder: (context) => MainPage()));
});
setState(() {
AlertDialog alert = AlertDialog(
title: Text("Error message"),
content: Text("Oops! The password is wrong or the email is invalid."),
actions: [
okButton,
],
);
showDialog(
context: context,
builder: (BuildContext context) {
return alert;
},
);
});
print(response.headers);
print(response.body);
}
}
推荐答案
当然,您可以为记住我
创建一个简单的复选框.在登录按钮中,您可以检查是否选中了此复选框.如果是这样,您可以设置电子邮件&共享首选项中的密码.
Of course, you can create a simple checkbox for remember me
. In the login button, you can check if this checkbox is checked. If it is, you can set email & password in shared_preferences.
下次,当用户再次出现时,您可以从shared_preferences自动获得这些字段.
Next time, when the user comes again you can get these fields automatically from shared_preferences.
此处是一个例子.
这篇关于无论如何要在flutter中使用sharedPreferences启用“记住我"功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!