import 'package:flutter/material.dart'; import 'package:flutter_tracker/dio/login_dao.dart'; import 'package:flutter_tracker/model/login_entity.dart'; import 'package:flutter_tracker/routes/routes.dart'; import 'package:flutter_tracker/utils/app_util.dart'; import 'package:shared_preferences/shared_preferences.dart'; /// Description: /// Time : 2021年12月03日 Friday /// Author : liuyuqi.gov@msncn class LoginPage extends StatefulWidget { const LoginPage({Key? key}) : super(key: key); @override _LoginPageState createState() => _LoginPageState(); } class _LoginPageState extends State { final TextEditingController _usernameController = TextEditingController(); final TextEditingController _passwordController = TextEditingController(); final _formKey = GlobalKey(); String? _username = ""; String? _password = ""; @override void initState() { super.initState(); loadData(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text('登录')), body: Padding( padding: EdgeInsets.symmetric(vertical: 16, horizontal: 24), child: Form( key: _formKey, child: Column( children: [ TextFormField( autofocus: true, controller: _usernameController, decoration: InputDecoration( labelText: '用户名', hintText: '请输入用户名', icon: Icon(Icons.person)), validator: (value) { if (value == null || value.isEmpty) { return '用户名不能为空'; } return null; }, onSaved: (value) { _username = value; }, ), TextFormField( controller: _passwordController, decoration: const InputDecoration( labelText: '密码', hintText: '请输入密码', icon: Icon(Icons.lock)), obscureText: true, validator: (value) { if (value == null || value.isEmpty) { return '密码不能为空'; } return null; }, onSaved: (value) { _password = value; }, ), Padding( padding: EdgeInsets.only(top: 28), child: Row( children: [ Expanded( child: ElevatedButton( style: ButtonStyle( padding: MaterialStateProperty.all(EdgeInsets.all(15)), iconColor: MaterialStateProperty.all(Colors.green), foregroundColor: MaterialStateProperty.all(Colors.white), ), 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 { SharedPreferences prefs = await SharedPreferences.getInstance(); if (_formKey.currentState!.validate() && _username != null && _password != null) { _formKey.currentState!.save(); LoginEntity loginEntity = await LoginDao.login(_username!, _password!); if (loginEntity.msgModel.success) { prefs.setString('username', _username!); prefs.setString('password', _password!); prefs.setBool('isLogin', true); Navigator.of(context).pushNamed(Routes.indexPage); } AppUtil.buildToast(loginEntity.msgModel.msg); } } }