123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596 |
- import 'package:flutter/material.dart';
- import 'package:shared_preferences/shared_preferences.dart';
- class LoginPage extends StatefulWidget {
- const LoginPage({Key key}) : super(key: key);
- @override
- _LoginPageState createState() => _LoginPageState();
- }
- class _LoginPageState extends State<LoginPage> {
- final TextEditingController _usernameController = TextEditingController();
- final TextEditingController _passwordController = TextEditingController();
- final _formKey = GlobalKey<FormState>();
- String _username;
- String _password;
- @override
- void initState() {
- super.initState();
- loadData();
- }
- @override
- Widget build(BuildContext context) {
- return Scaffold(
- appBar: AppBar(title: Text('登录')),
- body: Form(
- key: _formKey,
- child: Column(
- children: <Widget>[
- TextFormField(
- controller: _usernameController,
- decoration: InputDecoration(
- labelText: '用户名',
- hintText: '请输入用户名',
- ),
- validator: (value) {
- if (value.isEmpty) {
- return '用户名不能为空';
- }
- return null;
- },
- onSaved: (value) {
- _username = value;
- },
- ),
- TextFormField(
- controller: _passwordController,
- decoration: InputDecoration(
- labelText: '密码',
- hintText: '请输入密码',
- ),
- obscureText: true,
- validator: (value) {
- if (value.isEmpty) {
- return '密码不能为空';
- }
- return null;
- },
- onSaved: (value) {
- _password = value;
- },
- ),
- RaisedButton(
- child: Text('登录'),
- onPressed: () {
- login();
- },
- ),
- ],
- ),
- ));
- }
- void loadData() async {
- SharedPreferences prefs = await SharedPreferences.getInstance();
- String username = prefs.getString('username');
- String password = prefs.getString('password');
- if (username != null && password != null) {
- _usernameController.text = username;
- _passwordController.text = password;
- }
- }
- void login() async {
- if (_formKey.currentState.validate()) {
- _formKey.currentState.save();
- SharedPreferences prefs = await SharedPreferences.getInstance();
- prefs.setString('username', _username);
- prefs.setString('password', _password);
- Navigator.of(context).pushReplacementNamed('/home');
- }
- }
- }
|