123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118 |
- import 'package:flutter/material.dart';
- import 'package:flutter_tracker/dio/login_dao.dart';
- import 'package:flutter_tracker/model/config.dart';
- import 'package:flutter_tracker/model/user_model.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: Padding(
- padding: EdgeInsets.symmetric(vertical: 16, horizontal: 24),
- child: Form(
- key: _formKey,
- child: Column(
- children: <Widget>[
- TextFormField(
- autofocus: true,
- controller: _usernameController,
- decoration: InputDecoration(
- labelText: '用户名',
- hintText: '请输入用户名',
- icon: Icon(Icons.person)),
- validator: (value) {
- if (value.isEmpty) {
- return '用户名不能为空';
- }
- return null;
- },
- onSaved: (value) {
- _username = value;
- },
- ),
- TextFormField(
- controller: _passwordController,
- decoration: InputDecoration(
- labelText: '密码',
- hintText: '请输入密码',
- icon: Icon(Icons.lock)),
- obscureText: true,
- validator: (value) {
- if (value.isEmpty) {
- return '密码不能为空';
- }
- return null;
- },
- onSaved: (value) {
- _password = value;
- },
- ),
- Padding(
- padding: EdgeInsets.only(top: 28),
- child: Row(
- children: [
- Expanded(
- child: RaisedButton(
- padding: EdgeInsets.all(15),
- color: Theme.of(context).primaryColor,
- textColor: 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 {
- if (_formKey.currentState.validate()) {
- _formKey.currentState.save();
- UserModel userModel = await LoginDao.login(_username, _password);
- if (userModel.username == "") {
- Config.pref.setString('username', _username);
- Config.pref.setString('password', _password);
- Config.pref.setBool('isLogin', true);
- Navigator.of(context).pushReplacementNamed('/home');
- } else {}
- }
- }
- }
|