【问题标题】:Anyway to enable 'remember me' function using sharedPreferences in flutter?无论如何在颤振中使用 sharedPreferences 启用“记住我”功能?
【发布时间】:2021-02-01 12:56:48
【问题描述】:

目前,如果用户成功登录一次,我已启用“继续登录”功能。但是,我仍然想制作一个“记住我”复选框来保存用户的成功登录信息。谁能帮我解决这个问题?

需要:如果用户成功登录一次,则允许用户存储电子邮件和密码的复选框。

代码如下:

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

【问题讨论】:

  • 你想保存什么样的信息?
  • @Creator 如果用户单击复选框并成功登录一次,则保存用户名(在本例中显示为电子邮件)和密码。
  • 我不建议您这样做,因为这会使您的应用极易受到黑客攻击。而且您的用户使用您的应用程序会感到不安全。我建议您只保存用户名或电子邮件。
  • @Creator 感谢您的提醒!但我仍然想知道在我的情况下该怎么做。
  • 首先创建一个记住我的按钮。然后是地图列表。其中包含每个用户登录到您的应用程序的用户名和密码。每次新用户登录时都会保存他的信息。

标签: flutter sharedpreferences


【解决方案1】:

当然,您可以为remember me 创建一个简单的复选框。在登录按钮中,您可以检查是否选中了此复选框。如果是,您可以在 shared_preferences 中设置电子邮件和密码。

下次用户再次访问时,您可以从 shared_preferences 中自动获取这些字段。

Here 就是一个例子。

【讨论】:

  • 您能否在这种情况下向我提供具体的编辑建议?非常感谢!
  • 好吧,看看这里,试着做点什么。 github.com/aaronksaunders/simple_firebase_auth
  • 是吗?你的意思是把它提交到你的文件中?
  • 是的。首先,您必须尝试向我们展示您编写的代码。
  • 你在吗?拉取请求已创建。
猜你喜欢
  • 2021-03-29
  • 1970-01-01
  • 2011-02-26
  • 1970-01-01
  • 1970-01-01
  • 2013-10-07
  • 2021-05-21
  • 2015-04-23
  • 2019-02-16
相关资源
最近更新 更多