Anyway to enable 'remember me' function using sharedPreferences in flutter?

ぃ、小莉子 提交于 2021-01-28 10:18:38

问题


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.

Code is shown below:

  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);
    }
  }

回答1:


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.

Next time, when the user comes again you can get these fields automatically from shared_preferences.

Here is an example.



来源:https://stackoverflow.com/questions/64415647/anyway-to-enable-remember-me-function-using-sharedpreferences-in-flutter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!