初學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 = "登錄成功 \n" + _userName.text;
            return AlertDialog(
              content: Text(sucess),
            );
          } else {
            String err = "登錄失敗 \n 賬號或密碼錯誤";
            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(
                width: 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-----------------------------------------------------------------------------------------------------

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM