login_page.dart 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. import 'package:flutter/material.dart';
  2. import 'package:shared_preferences/shared_preferences.dart';
  3. class LoginPage extends StatefulWidget {
  4. const LoginPage({Key key}) : super(key: key);
  5. @override
  6. _LoginPageState createState() => _LoginPageState();
  7. }
  8. class _LoginPageState extends State<LoginPage> {
  9. final TextEditingController _usernameController = TextEditingController();
  10. final TextEditingController _passwordController = TextEditingController();
  11. final _formKey = GlobalKey<FormState>();
  12. String _username;
  13. String _password;
  14. @override
  15. void initState() {
  16. super.initState();
  17. loadData();
  18. }
  19. @override
  20. Widget build(BuildContext context) {
  21. return Scaffold(
  22. appBar: AppBar(title: Text('登录')),
  23. body: Form(
  24. key: _formKey,
  25. child: Column(
  26. children: <Widget>[
  27. TextFormField(
  28. controller: _usernameController,
  29. decoration: InputDecoration(
  30. labelText: '用户名',
  31. hintText: '请输入用户名',
  32. ),
  33. validator: (value) {
  34. if (value.isEmpty) {
  35. return '用户名不能为空';
  36. }
  37. return null;
  38. },
  39. onSaved: (value) {
  40. _username = value;
  41. },
  42. ),
  43. TextFormField(
  44. controller: _passwordController,
  45. decoration: InputDecoration(
  46. labelText: '密码',
  47. hintText: '请输入密码',
  48. ),
  49. obscureText: true,
  50. validator: (value) {
  51. if (value.isEmpty) {
  52. return '密码不能为空';
  53. }
  54. return null;
  55. },
  56. onSaved: (value) {
  57. _password = value;
  58. },
  59. ),
  60. RaisedButton(
  61. child: Text('登录'),
  62. onPressed: () {
  63. login();
  64. },
  65. ),
  66. ],
  67. ),
  68. ));
  69. }
  70. void loadData() async {
  71. SharedPreferences prefs = await SharedPreferences.getInstance();
  72. String username = prefs.getString('username');
  73. String password = prefs.getString('password');
  74. if (username != null && password != null) {
  75. _usernameController.text = username;
  76. _passwordController.text = password;
  77. }
  78. }
  79. void login() async {
  80. if (_formKey.currentState.validate()) {
  81. _formKey.currentState.save();
  82. SharedPreferences prefs = await SharedPreferences.getInstance();
  83. prefs.setString('username', _username);
  84. prefs.setString('password', _password);
  85. Navigator.of(context).pushReplacementNamed('/home');
  86. }
  87. }
  88. }