简体   繁体   English

如何使用path_provider包在flutter中构建登录页面以将登录信息存储在本地文件中

[英]How to build a login page in flutter using path_provider package for storing login in local file

I have created a save method and read method for storing credentials.我创建了用于存储凭据的保存方法和读取方法。

In the code below username and password are going to be saved in a file.在下面的代码中, usernamepassword将保存在一个文件中。

Code is also giving the directory path where it is going to be stored but it is not working properly while tapping on the login button.代码还提供了将要存储的目录路径,但在点击登录按钮时它无法正常工作。 The code represents the login screen which appears when we open the app for the first time.该代码代表我们第一次打开应用程序时出现的登录屏幕。 The user account login page will open after filling the credentials.填写凭据后,将打开用户帐户登录页面。 It will never ask to the user for logins till the user clear the data or uninstall the app.在用户清除数据或卸载应用程序之前,它永远不会要求用户登录。 In this code username and password are the text filed, their is a checkbox in the login screen which will act as a remember me box.在这段代码中, usernamepassword是文本文件,它们是登录屏幕中的一个复选框,它将充当记住我的框。 It will call the save method on click and now I want that checkbox will save credentials only after pressing the login button.它将在单击时调用保存方法,现在我希望该复选框仅在按下登录按钮后才保存凭据。

  class  LoginPageState extends State<LoginPage> {
  TextEditingController username = new TextEditingController();
  TextEditingController password = new TextEditingController();

  bool checkValue = false;
  String user ="username";
  String pass="password";


 @override
  void initState() {
    super.initState();
    // call credentials method
    readuser().then((String value) {
      setState(() {
        user="username";
        user = value;
      });
    });
    readpass().then((String value) {
      setState(() {
        pass="password";
        pass = value;
      });
    });
  }

  bool checkingdata() {
    if (user.length !=0 && pass.length != 0) {
      return true;
    } else {
      return false;
    }
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        elevation: 0.0,
        backgroundColor: Colors.white12,
      ),
      body: new SingleChildScrollView(
        child: _body(),
        scrollDirection: Axis.vertical,
      ),
    );
  }

  Widget _body() {
    return new Container(
      padding: EdgeInsets.only(right: 20.0, left: 20.0),
      child: new Column(
        mainAxisAlignment: MainAxisAlignment.start,
        children: <Widget>[
          new Container(
            margin: EdgeInsets.all(30.0),
            child: new Image.asset(
              "assets/images/flutter_icon.png",
              height: 100.0,
            ),
          ),
          new TextField(
            onSubmitted: (_) {
              setState(() {
                user = username.text;``
              });
            },
            controller: username,
            decoration: InputDecoration(
                hintText: "username",
                hintStyle: new TextStyle(color: Colors.grey.withOpacity(0.3))),
          ),
          new TextField(
              controller: password,
              obscureText: true,
              onSubmitted: (_) {
                setState(() {
                  pass = password.text;
                });
              },
              decoration: InputDecoration(
                  hintText: "password",
                  hintStyle:
                  new TextStyle(color: Colors.grey.withOpacity(0.3)))),
          new CheckboxListTile(
           value: checkValue,

            title: new Text("Remember me"),
            controlAffinity: ListTileControlAffinity.leading,
            onChanged: (bool value) { checkingdata();

              _saved(user, pass);
            },
          ),
          new Container(
            decoration:
            new BoxDecoration(border: Border.all(color: Colors.black)),
            child: new ListTile(
              title: new Text(
                "Login",
                textAlign: TextAlign.center,
              ),
              onTap: _saved(user, pass),
            ),
          )
        ],
      ),
    );
  }

  //for username
  _saved (String text,String text2) async {
    print("asggd");
    final userfile = await _localFile;
      //print("asd");
    // Write the file.
    _savedpass(text2);
    print("asded");

    return userfile.writeAsString(text);
  }
  //for password
  _savedpass(String text) async {
    final passfile = await _localFile;
    // Write the file.
    return passfile.writeAsString(text);
  }

  Future<String> readuser() async {
    try {
      final userfile = await _localFile;


      // Read the file.
      String contents = await userfile.readAsString();

      return contents;
    } catch (e) {
      // If encountering an error, return 0.
     //return "dfd";
    }
  }

  Future<String> readpass() async {
    try {
      final userpass = await _localFile;


      // Read the file.
      String contents = await userpass.readAsString();

      return contents;
    } catch (e) {
      // If encountering an error, return 0.
      //return;
    }
  }Future<String> get _localPath async {
    final directory = await getApplicationDocumentsDirectory();
    return directory.path;
  }
  Future<File> get _localFile async {
  var _localPath;
  final path = await _localPath;
  return File('$path/counter.txt');
}
}

Read function is used for the testing purposes.读取功能用于测试目的。 It will print the login credential on the home screen.它将在主屏幕上打印登录凭据。 I also want to add one more method in this code which is used to check the saved login credentials form the file so that next time when you reuse the app it will directly open the home screen.我还想在此代码中添加另一个方法,用于检查文件中保存的登录凭据,以便下次重用该应用程序时,它将直接打开主屏幕。

Putting aside the fact that you want to store your credentials in plaintext in a local file, your problem is your _localFile getter.撇开您想将凭证以明文形式存储在本地文件中的事实不谈,您的问题是您的_localFile getter。 You define a local variable _localPath, so in the next line of code, all you're getting is null .您定义了一个局部变量 _localPath,因此在下一行代码中,您得到的只是null Also, you probably want to create your file if it doesn't exist, simply by calling file.create() .此外,如果文件不存在,您可能想要创建文件,只需调用file.create()

you may not have the file counter.txt , so you need to create it first.您可能没有counter.txt文件,因此您需要先创建它。 I would advise you to use shared_preferences or hive to store your data.我建议您使用shared_preferenceshive来存储您的数据。

For example with shared_preferences it will looks like in snippet below:例如,对于 shared_preferences,它看起来像下面的代码片段:

To retrieve data检索数据

final prefs = await SharedPreferences.getInstance();

final login = prefs.getString('login');
final password = prefs.getString('password');

// It's important to check it to the null

if (login != null && password != null) {
  // Use it
}

To store new data存储新数据

final prefs = await SharedPreferences.getInstance();

await prefs.setString('login', login);
await prefs.setString('password', password);

And you can remove from the preference as well:您也可以从首选项中删除:

final prefs = await SharedPreferences.getInstance();

await prefs.remove('login');
await prefs.remove('password');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM