flutter TextField 輸入框組件

這是我參與8月更文挑戰的第7天,活動詳情查看:8月更文挑戰javascript

TextField

顧名思義文本輸入框,相似於iOS中的UITextField和Android中的EditText和Web中的TextInput。主要是爲用戶提供輸入文本提供方便。相信你們在原生客戶端上都用過這個功能,就不在作具體介紹了,接下來仍是具體介紹下Flutter中TextField的用法。java

如下內容已更新到 githubgit

TextField的構造方法:github

const TextField({
    Key key,
    this.controller,            //控制器,控制TextField文字
    this.focusNode,
    this.decoration: const InputDecoration(),      //輸入器裝飾
    TextInputType keyboardType: TextInputType.text, //輸入的類型
    this.style,
    this.textAlign: TextAlign.start,
    this.autofocus: false,
    this.obscureText: false,  //是否隱藏輸入
    this.autocorrect: true,
    this.maxLines: 1,
    this.maxLength,
    this.maxLengthEnforced: true,
    this.onChanged,            //文字改變觸發
    this.onSubmitted,          //文字提交觸發(鍵盤按鍵)
    this.onEditingComplete,  //當用戶提交可編輯內容時調用
    this.inputFormatters,
    this.enabled,
    this.cursorWidth = 2.0,
    this.cursorRadius,
    this.cursorColor,
    this.keyboardAppearance,
  })
複製代碼

先來試試最基本的TextField:api

/*
 * Created by 李卓原 on 2018/9/7.
 * email: zhuoyuan93@gmail.com
 *
 */
 
import 'package:flutter/material.dart';

class TextFieldAndCheckPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => TextFieldAndCheckPageState();
}

class TextFieldAndCheckPageState extends State<TextFieldAndCheckPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(appBar: AppBar(
      title: Text('輸入和選擇'),
    ),body:TextField(),
    );
  }
}

複製代碼

輸入框 這是一個默認的輸入框,咱們什麼都沒有作的時候的樣子. 而後咱們試一下它的屬性markdown

TextField(
        keyboardType: TextInputType.number,
        decoration: InputDecoration(
          contentPadding: EdgeInsets.all(10.0),
          icon: Icon(Icons.text_fields),
          labelText: '請輸入你的姓名)',
          helperText: '請輸入你的真實姓名',
        ),
        onChanged: _textFieldChanged,
        autofocus: false,
      ),


  void _textFieldChanged(String str) {
    print(str);
  }
複製代碼

咱們增長一個keyboardType屬性,把keyboardType設置爲TextInputType.number 能夠看到每次咱們讓TextField得到焦點的時候彈出的鍵盤就變成了數字優先了。 而後咱們爲輸入框作一些其餘的效果,如提示文字,icon、標籤文字等。 咱們給上面的代碼新增decoration屬性,設置相關屬性,能夠發現當咱們的TextField得到焦點時,圖標會自動變色,提示文字會自動上移。app

這裏寫圖片描述

還能夠看到 我加了一個onChangedonChanged是每次輸入框內每次文字變動觸發的回調,onSubmitted是用戶提交而觸發的回調。 每當用戶改變輸入框內的文字,都會在控制檯輸出如今的字符串.與onSubmitted用法相同.ide

接下來,咱們實現一個簡單的登陸頁面:oop

/*
 * Created by 李卓原 on 2018/9/7.
 * email: zhuoyuan93@gmail.com
 *
 */

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class TextFieldAndCheckPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => TextFieldAndCheckPageState();
}

class TextFieldAndCheckPageState extends State<TextFieldAndCheckPage> {
  //手機號的控制器
  TextEditingController phoneController = TextEditingController();

  //密碼的控制器
  TextEditingController passController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('輸入和選擇'),
      ),
      body: Column(
        children: <Widget>[
          TextField(
            controller: phoneController,
            keyboardType: TextInputType.number,
            decoration: InputDecoration(
              contentPadding: EdgeInsets.all(10.0),
              icon: Icon(Icons.phone),
              labelText: '請輸入你的用戶名)',
              helperText: '請輸入註冊的手機號',
            ),
            autofocus: false,
          ),
          TextField(
              controller: passController,
              keyboardType: TextInputType.number,
              decoration: InputDecoration(
                contentPadding: EdgeInsets.all(10.0),
                icon: Icon(Icons.lock),
                labelText: '請輸入密碼)',
              ),
              obscureText: true),
          RaisedButton(
            onPressed: _login,
            child: Text('登陸'),
          ),
        ],
      ),
    );
  }

  void _login() {
    print({'phone': phoneController.text, 'password': passController.text});
    if (phoneController.text.length != 11) {
      showDialog(
          context: context,
          builder: (context) => AlertDialog(
                title: Text('手機號碼格式不對'),
              ));
    } else if (passController.text.length == 0) {
      showDialog(
          context: context,
          builder: (context) => AlertDialog(
                title: Text('請填寫密碼'),
              ));
    } else {
      showDialog(
          context: context,
          builder: (context) => AlertDialog(
                title: Text('登陸成功'),
              ));
      phoneController.clear();
    }
  }

  void onTextClear() {
    setState(() {
      phoneController.clear();
      passController.clear();
    });
  }
}

複製代碼

這裏寫圖片描述

在佈局上,咱們使用一個Column包含了兩個TextField和一個RaisedButton。 在邏輯上,每當咱們點擊下面的按鈕都會判斷用戶名密碼是否符合要求,而且使用控制器清空已經輸入的用戶名和密碼。佈局

當用戶輸入的手機號碼不是11位的時候提示手機號碼格式錯誤, 當用戶沒有輸入密碼時,提示填寫密碼, 用戶名和密碼符合要求時提示登陸成功。

我這裏登陸成功以後還調了一個方法:phoneController.clear() 清空了用戶名輸入框中的內容。

代碼的邏輯很簡單。關於TextField的其餘用法就不在一一介紹了,有興趣的小夥伴能夠本身嘗試下.

使用decoration美化輸入框

先看一下效果:

這裏寫圖片描述

代碼:

TextField(
            controller: accountController,
            decoration: InputDecoration(
              border: OutlineInputBorder(),
              hintText: '請輸入帳號',
              labelText: '左上角',
              prefixIcon: Icon(Icons.person),
            ),
          )
複製代碼

在這裏插入圖片描述 能夠看到,我先添加了一個decoration屬性.

decoration屬性介紹:

border:增長一個邊框, hintText:未輸入文字時,輸入框中的提示文字, prefixIcon:輸入框內側左面的控件, labelText:一個提示文字。輸入框獲取焦點/輸入框有內容 會移動到左上角,不然在輸入框內,labelTex的位置. suffixIcon: 輸入框內側右面的圖標. icon : 輸入框左側添加個圖標

在多個輸入框內切換焦點

介紹一下onEditingComplete這個方法:

當用戶提交可編輯內容時調用(例如,用戶按下鍵盤上的「done」按鈕)。

onEditingComplete的默認實現根據狀況執行2種不一樣的行爲:

  • 當完成操做被按下時,例如「done」、「go」、「send」或「search」,用戶的內容被提交給[controller],而後焦點被放棄。
  • 當按下一個未完成操做(如「next」或「previous」)時,用戶的內容被提交給[controller],但不會放棄焦點,由於開發人員可能但願當即將焦點轉移到[onsubmit]中的另外一個輸入小部件。

在這裏插入圖片描述

咱們有時候會須要這樣的狀況, 好比一個登陸頁面, 須要輸入帳號和密碼 , 天然輸入完帳號就要輸入密碼了 , 咱們在輸入帳號結束的時候 , 讓密碼輸入框獲取到焦點 .

看一下代碼:

...
  FocusNode secondTextFieldNode = FocusNode();
...
Column(
        children: <Widget>[
          TextField(
            /* onChanged: (text) {
          value = text;
          print(value);
        },*/
            autofocus: false, //是否自動獲取焦點
            controller: _textController,
            decoration: InputDecoration(
              suffixIcon: Icon(Icons.chevron_right), //輸入框內右側圖標
              icon: Icon(Icons.person), //輸入框左側圖標
              prefixIcon: Icon(Icons.skip_previous), //輸入框內左側圖標
              labelText: 'labelText',
              hintText: 'hintText',
              helperText: 'helperText',
            ),
            onEditingComplete: () =>
                FocusScope.of(context).requestFocus(secondTextFieldNode),
          ),
          TextField(
            focusNode: secondTextFieldNode,
            decoration: InputDecoration(
                contentPadding: EdgeInsets.symmetric(horizontal: 15.0)),
          ),
        ],
      ),
複製代碼

我在頂層建立了一個交電接點並附加給第二個輸入框, 在第一個輸入框的onEditingComplete方法中是用

FocusScope.of(context).requestFocus(secondTextFieldNode),
複製代碼

方法來讓第二個輸入框請求獲取焦點, 固然你也能夠添加個按鈕 , 點擊按鈕執行這個方法來實現切換焦點的功能.

例如: [外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-BjSYHYmc-1573730655449)(cdn-images-1.medium.com/max/800/1*v…)] 代碼很簡單,我就不貼了.

keyboardType

TextField成爲焦點時顯示的鍵盤類型。

TextField(
  keyboardType: TextInputType.number,
),
複製代碼

類型是:

  • TextInputType.text(普通完整鍵盤)
  • TextInputType.number(數字鍵盤)
  • TextInputType.emailAddress(帶有「@」的普通鍵盤)
  • TextInputType.datetime(帶有「/」和「:」的數字鍵盤)
  • TextInputType.multiline(帶有選項以啓用有符號和十進制模式的數字鍵盤)

TextInputAction

更改TextField的textInputAction能夠更改鍵盤自己的操做按鈕。

TextField(
  textInputAction: TextInputAction.search,
),
複製代碼

這會致使「完成」按鈕被「搜索」按鈕替換:

在這裏插入圖片描述

TextCapitalization

TextField提供了一些有關如何使用戶輸入中的字母大寫的選項。

  • TextCapitalization.sentences : 這是咱們指望的正常類型的大寫,每一個句子的首字母大寫。

在這裏插入圖片描述

  • TextCapitalization.characters:大寫句子中的全部字符。

[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-4ykAhgu0-1573730655451)(cdn-images-1.medium.com/max/800/1*S…)]

  • TextCapitalization.words : 將每一個單詞的首字母大寫。

在這裏插入圖片描述

更改TextField中的光標

能夠直接從TextField小部件自定義遊標。

能夠更改角落的光標顏色,寬度和半徑。 例如,這裏我沒有明顯的緣由製做一個圓形的紅色光標。

TextField(
  cursorColor: Colors.red,
  cursorRadius: Radius.circular(16.0),
  cursorWidth: 16.0,
),
複製代碼

在這裏插入圖片描述

控制TextField中的大小和最大長度

TextFields能夠控制在其中寫入的最大字符數,最大行數並在鍵入文本時展開。

TextField(
  maxLength: 4,
),
複製代碼

在這裏插入圖片描述

經過設置maxLength屬性,將強制執行最大長度,而且默認狀況下會將計數器添加到TextField。

github源碼

相關文章
相關標籤/搜索