Flutter TextField詳解

效果:
在這裏插入圖片描述

終於還是對TextField下手了,這個屬性最多、功能點最多的Widget。

基本屬性

TextField是一個material design風格的輸入框,本身有多種屬性,除此之外裝飾器InputDecoration也有多種屬性,但都比較簡單,所以不必擔心,且聽我娓娓道來。

先看一下源碼,重要或常用的屬性會有註釋。

TextField

  const TextField({
    Key key,
    this.controller,//控制器
    this.focusNode,//焦點
    this.decoration = const InputDecoration(),//裝飾
    TextInputType keyboardType,//鍵盤類型,即輸入類型
    this.textInputAction,//鍵盤按鈕
    this.textCapitalization = TextCapitalization.none,//大小寫
    this.style,//樣式
    this.strutStyle,
    this.textAlign = TextAlign.start,//對齊方式
    this.textDirection,
    this.autofocus = false,//自動聚焦
    this.obscureText = false,//是否隱藏文本,即顯示密碼類型
    this.autocorrect = true,//自動更正
    this.maxLines = 1,//最多行數,高度與行數同步
    this.minLines,//最小行數
    this.expands = false,
    this.maxLength,//最多輸入數,有值後右下角就會有一個計數器
    this.maxLengthEnforced = true,
    this.onChanged,//輸入改變回調
    this.onEditingComplete,//輸入完成時,配合TextInputAction.done使用
    this.onSubmitted,//提交時,配合TextInputAction
    this.inputFormatters,//輸入校驗
    this.enabled,//是否可用
    this.cursorWidth = 2.0,//光標寬度
    this.cursorRadius,//光標圓角
    this.cursorColor,//光標顏色
    this.keyboardAppearance,
    this.scrollPadding = const EdgeInsets.all(20.0),
    this.dragStartBehavior = DragStartBehavior.start,
    this.enableInteractiveSelection,
    this.onTap,//點擊事件
    this.buildCounter,
    this.scrollPhysics,
  }) 

參數很多,其實日常開發中連一半的屬性都用不到,但還是會盡量多的介紹。

InputDecoration

  const InputDecoration({
    this.icon,//左側外的圖標
    this.labelText,//懸浮提示,可代替hintText
    this.labelStyle,//懸浮提示文字的樣式
    this.helperText,//幫助文字
    this.helperStyle,
    this.hintText,//輸入提示
    this.hintStyle,
    this.hintMaxLines,
    this.errorText,//錯誤提示
    this.errorStyle,
    this.errorMaxLines,
    this.hasFloatingPlaceholder = true,//是否顯示懸浮提示文字
    this.isDense,
    this.contentPadding,//內填充
    this.prefixIcon,//左側內的圖標
    this.prefix,
    this.prefixText,//左側內的文字
    this.prefixStyle,
    this.suffixIcon,//右側內圖標
    this.suffix,
    this.suffixText,
    this.suffixStyle,
    this.counter,//自定義計數器
    this.counterText,//計數文字
    this.counterStyle,//計數樣式
    this.filled,//是否填充
    this.fillColor,//填充顏色
    this.errorBorder,
    this.focusedBorder,
    this.focusedErrorBorder,
    this.disabledBorder,
    this.enabledBorder,
    this.border,//邊框
    this.enabled = true,
    this.semanticCounterText,
    this.alignLabelWithHint,
  })

參數很多,多爲一個小功能點的圖標、文字和樣式,並不複雜。

ok,基本屬性大概過一遍,腦子裏有個印象就行了。下面開始實操。

樣式

基礎樣式

			TextField(),

很簡單,無任何參數,當然效果也很簡單。
在這裏插入圖片描述
style可以修改樣式。

隱藏文本

修改obscureText屬性值

              TextField(
                obscureText: true,
              ),

在這裏插入圖片描述
可以看到輸入的內容已經不可見了,變成常見的密碼類型了。

鍵盤類型

鍵盤類型 即 可輸入的類型,比如number就只能輸入數字

              TextField(
                keyboardType: TextInputType.number,
              ),

在這裏插入圖片描述
TextInputType可選類型:

  • text
  • multiline
  • number
  • phone
  • datetime
  • emailAddress
  • url

鍵盤按鈕

即鍵盤右下角的按鈕,常見的比如完成,右下角是一個完成的對號按鈕,上圖即是。

              TextField(
                textInputAction: TextInputAction.done,
              ),

TextInputAction其他選項:

  • none
  • unspecified
  • done
  • go
  • search
  • send
  • next
  • previous
  • continueAction
  • join
  • route
  • emergencyCall
  • newline

大小寫

即控制輸入的英文字母大小寫,比如單詞首字母大寫

              TextField(
                textCapitalization: TextCapitalization.words,
              ),

在這裏插入圖片描述
TextCapitalization的其他選項:

  • words:單詞首字母大寫
  • sentences:句子的首字母大寫
  • characters:所有字母大寫
  • none:默認無

光標

默認是一個藍色的豎線

              TextField(
                cursorColor: Colors.orange,
                cursorWidth: 15,
                cursorRadius: Radius.circular(15),
              ),

在這裏插入圖片描述

最多行數

設置最多3行

              TextField(
                maxLines: 3,
              ),

在這裏插入圖片描述
從效果可以看出,TextField高度已經變成了3行。但是我只是想最多輸入3行,默認還是1行的高度怎麼辦呢?
不用慌,加一個參數就行了: minLines

              TextField(
                maxLines: 3,
                minLines: 1,
              ),

在這裏插入圖片描述
可以看到,TextField的高度是會自適應的。

計數器

即右下角會有一個計數

              TextField(
                maxLength: 8,
              ),

在這裏插入圖片描述
默認:當前輸入長度/最大長度,那這個地方我們能不能改呢,當然可以,下面簡單操作一下

              TextField(
                maxLength: 8,
                decoration: InputDecoration(
                  counter: Text("自定義計數 0/100"),
                ),
              ),

在這裏插入圖片描述
這裏我用到了裝飾InputDecoration下的counter,類型是widget,那擴展度就相當高了,我只用了一個Text,別的widget也是可以的。

如果只是純文字的話,InputDecoration下還有一個counterText屬性和counterStyle

圖標

圖標有3種:

  • 左側外的圖標
              TextField(
                decoration: InputDecoration(
                  icon: Icon(Icons.person),
                ),
              ),

在這裏插入圖片描述

  • 左側內圖標
              TextField(
                decoration: InputDecoration(
                  prefixIcon: Icon(Icons.phone_android),
                ),
              ),

在這裏插入圖片描述

  • 右側內圖標
              TextField(
                decoration: InputDecoration(
                  suffixIcon: IconButton(
                    icon: Icon(Icons.close),
                    onPressed: () {
                      controller.clear();
                    },
                  ),
                ),
              ),

在這裏插入圖片描述

在右側圖標加了一個IconButton,因爲帶有點擊事件,我們可以在點擊的時候清除TextField中的內容。

以上就是圖標的介紹,其實除了圖標之外,對應的位置也可以顯示文字或者自定義顯示其他widget
比如出了prefixIcon之外還有其他3個屬性,用法跟上面介紹到的自定義計數器是一樣的。

    this.prefix,
    this.prefixText,
    this.prefixStyle,

提示文字

提示文字有4種:

  • 輸入提示文字
              TextField(
                controller: controller,
                decoration: InputDecoration(
                  hintText: '請輸入賬號aaa',
                ),
              ),

在這裏插入圖片描述

  • 懸浮提示文字
              TextField(
                controller: controller,
                decoration: InputDecoration(
                  hintText: '請輸入賬號aaa',
                  labelText: '請輸入賬號',
                ),
              ),

在這裏插入圖片描述
可以看到,默認顯示labelText,聚焦之後才顯示hintText,所以labelText是可以取代hintText的。

  • 幫助提示文字
              TextField(
                controller: controller,
                decoration: InputDecoration(
                  helperText: "幫助文字",
                  helperStyle: TextStyle(color: Colors.blue)
                ),
              ),

在這裏插入圖片描述
一直顯示在左下方

  • 錯誤提示文字
              TextField(
                controller: controller,
                decoration: InputDecoration(
                  errorText: "你沒有輸入任何內容",
                ),
              ),

在這裏插入圖片描述

去除下劃線

              TextField(
                decoration: InputDecoration.collapsed(hintText: "無下劃線的輸入框"),
              ),

在這裏插入圖片描述
也可以decoration: null, 差別就是沒有hintText了

邊框

              TextField(
                decoration: InputDecoration(
                  border: OutlineInputBorder(),
                ),
              ),

在這裏插入圖片描述
如果這個圓角不喜歡的話,也可以改一下的,比如:

              TextField(
                decoration: InputDecoration(
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.all(Radius.circular(30)),
                  ),
                ),
              ),

在這裏插入圖片描述

獲取輸入內容

有兩種方式:

  • onChanged
    onChanged是輸入內容改變時的回調,返回一個String類型的數值,可以用一個變量記一下
              TextField(
                onChanged: (text) {
                  print("輸入改變時" + text);
                },
              ),
  • controller
    即控制器,初始化:
  var controller;

  @override
  void initState() {
    super.initState();
    controller = TextEditingController();
    controller.addListener(() {});
  }

配置給TextField

              TextField(
                controller: controller,
              ),

獲取內容

controller.text

在事件中調用controller.text即返回輸入內容。

關閉軟鍵盤

往往我們在事件中提交的時候,是需要關閉軟鍵盤的

這裏我們就用到了focusNode

初始化:

FocusNode userFocusNode = FocusNode();

配置:

              TextField(
                focusNode: userFocusNode,
              ),

然後在需要的地方調用:

userFocusNode.unfocus();

校驗

校驗的話其實有個inputFormatters屬性

  final List<TextInputFormatter> inputFormatters;

繼續看TextInputFormatter源碼,有3個子類:

  • BlacklistingTextInputFormatter
  • WhitelistingTextInputFormatter
  • LengthLimitingTextInputFormatter

黑名單、白名單和長度限制,我們隨便找一個看一下源碼是怎麼實現校驗的:

往下看會看到這麼一段代碼:

  static final BlacklistingTextInputFormatter singleLineFormatter
      = BlacklistingTextInputFormatter(RegExp(r'\n'));

關鍵詞在RegExp,其實就是我們一般用的正則表達式而已。

這樣的話,我們也可以自定義校驗規則了,比如校驗手機號:

  String validateMobile(String value) {
    String patttern = r'(^[0-9]*$)';
    RegExp regExp = new RegExp(patttern);
    if (value.length == 0) {
      return "手機號爲空";
    } else if (!regExp.hasMatch(value)) {
      return "手機號格式不正確";
    }
    return null;
  }

以上只是我們一般的校驗,表單的話還是建議使用From包裹TextFormField

異常

  • 軟鍵盤彈出之後遮蓋
  • 軟鍵盤彈出之後高度溢出

解決辦法:用滑動組件包裹起來(ListView等),這樣軟鍵盤彈出的時候,輸入框也會自動向上滑。


總結

以上就是全部介紹了,然後寫了個登錄註冊的小demo:
在這裏插入圖片描述

github:https://github.com/yechaoa/wanandroid_flutter/blob/master/lib/pages/loginPage.dart

官方文檔:https://api.flutter.dev/flutter/material/TextField-class.html


寫作不易,有用就隨手點個贊或star唄


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章