zoukankan      html  css  js  c++  java
  • 初学Flutter 一个登录界面

    首先先上全部代码:

    import 'package:flutter/material.dart';
    import 'package:shared_preferences/shared_preferences.dart';
    void main() => runApp(MyApp());
    
    class MyApp extends StatelessWidget {
      // This widget is the root of your application.
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: '登录界面',
          theme: ThemeData(
            primarySwatch: Colors.blue,
          ),
          home: MyHomePage(title: '登录界面'),
        );
      }
    }
    
    class MyHomePage extends StatefulWidget {
      MyHomePage({Key key, this.title}) : super(key: key);
    
      final String title;
    
      @override
      _MyHomePageState createState() => _MyHomePageState();
    }
    
    class _MyHomePageState extends State<MyHomePage> {
      final _userName = TextEditingController(); //用户名
      final _userPwd = TextEditingController(); //密码
      GlobalKey _globalKey = new GlobalKey<FormState>(); //用于检查输入框是否为空
    
      void _login() {
        showDialog(
            context: context,
            builder: (context) {
              if (_userName.text == "admin" && _userPwd.text == "123456") {
                String sucess = "登录成功 
    " + _userName.text;
                return AlertDialog(
                  content: Text(sucess),
                );
              } else {
                String err = "登录失败 
     账号或密码错误";
                return AlertDialog(
                  content: Text(err),
                );
              }
            });
      }
      // 保存账号密码
      void _saveLoginMsg() async{
          SharedPreferences preferences=await SharedPreferences.getInstance();
          preferences.setString("name", _userName.text);
          preferences.setString("pwd", _userPwd.text);
      }
      // 读取账号密码,并将值直接赋给账号框和密码框
      void _getLoginMsg()async{
        SharedPreferences preferences=await SharedPreferences.getInstance();
        _userName.text=preferences.get("name");
        _userPwd.text=preferences.get("pwd");
      }
      @override
      void initState(){
        super.initState();
        _getLoginMsg();
      }
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text(widget.title),
          ),
          body: Center(
            child: Form(
              key: _globalKey,
              autovalidate: true, //自动校验
              child: Column(
                children: <Widget>[
                  TextFormField(
                    controller: _userName,
                    decoration: InputDecoration(
                        labelText: "账号",
                        hintText: "输入你的账号",
                        icon: Icon(Icons.person)),
                    validator: (v) {
                      return v.trim().length > 0 ? null : "用户名不能为空";
                    },
                  ),
                  TextFormField(
                    controller: _userPwd,
                    decoration: InputDecoration(
                      labelText: "密码",
                      hintText: "输入你的密码",
                      icon: Icon(Icons.lock),
                    ),
                    validator: (v) {
                      return v.trim().length > 5 ? null : "密码不低于6位";
                    },
                    obscureText: true,
                  ),
                  Padding(
                    padding: EdgeInsets.only(top: 20.0),
                  ),
                  SizedBox(
                     120.0,
                    height: 50.0,
                    child: RaisedButton(
                      onPressed: () {
                        if ((_globalKey.currentState as FormState).validate()) {
                          _login();
                          _saveLoginMsg();
                        }
                      },
                      child: Text(
                        "登录",
                        style: TextStyle(color: Colors.white), //字体白色
                      ),
                      color: Colors.blue,
                    ),
                  ),
                ],
              ),
            ),
          ),
        );
      }
    }

      

     效果图

    代码都很简单,相信即便是和我一样第一次接触这个语言的也能很快看懂

      

    然后接下来我们给它加个记住密码的功能,设计思路,通过SharedPreferences存储,

    点击登录的时候将账号密码报存到本地,,然后在打开软件的时候加载

    flutter需要在pubspec.yaml 添加依赖

    shared_preferences: "^0.4.2"

    因为我这里用的是vs code编写,所以添加后只需要按 Ctrl+S就会自动添加依赖

     如果你用的是Android Studio 或者IDEA,点击Packages get,就会把你需要的包给依赖好

    然后在代码中引入 

    import 'package:shared_preferences/shared_preferences.dart';

    添加这两个方法

      // 保存账号密码
      void _saveLoginMsg() async{
          SharedPreferences preferences=await SharedPreferences.getInstance();
          preferences.setString("name", _userName.text);
          preferences.setString("pwd", _userPwd.text);
      }
      // 读取账号密码,并将值直接赋给账号框和密码框
      void _getLoginMsg()async{
        SharedPreferences preferences=await SharedPreferences.getInstance();
        _userName.text=preferences.get("name");
        _userPwd.text=preferences.get("pwd");
      }

    在登录按钮的单击事件那里添加一个把 _saveLoginMsg的方法添加进去

    好了,现在可以保持了,现在只剩最后一个问题了,就是在开启软件的时候就获取保存好的账号密码.

    在这里我使用的是Flutter的生命周期

    我们先来看下Android原生的生命周期

    在Android原生中有个onCreate()的方法,这个方法是在App启动是立即执行它下面的方法。那么在flutter中有没有类似的方法呢,答案是肯定的,有!我们来看看Flutter的生命周期

    在Flutter中initState的方法起到的作用是和onCreate()是一样的,所以我们只需要在它下面调用getLoginMsg()方法就可以。

     没错,就这么简单,如果对你有什么帮助麻烦点个赞,文中有哪些不足欢迎大神指教定虚心接受

      @override
      void initState(){
        super.initState();
        _getLoginMsg();
      }

     -------------------------------------------------------------------------------------------------------LJX 2019-10-26-----------------------------------------------------------------------------------------------------

  • 相关阅读:
    ocx文件转换成C#程序引用的DLL
    CSS颜色代码 颜色值 颜色名字大全(转载)
    WinForm轻松实现自定义分页 (转载)
    如何:使用PicturBox实现类似淘宝网站图片的局部放大功能
    转载jQuery图片放大插件[twiPicZoom]
    LINQ查询返回DataTable类型
    最喜欢的VS 键盘快捷键摘抄
    Codeforces Round #336 (Div. 2)B 暴力 C dp D 区间dp
    Educational Codeforces Round 24 A 水 B stl C 暴力 D stl模拟 E 二分
    poj 1185 状态压缩
  • 原文地址:https://www.cnblogs.com/inthecloud/p/11742861.html
Copyright © 2011-2022 走看看