小菜最近在學習基礎的 Flutter Widget,原因在于很多基礎的元件有很多容易忽視的注意事項,了解并熟悉後對整體的開發認知會有所提升;今天小菜學習一下 TextField 文本輸入框;
源碼分析
const TextField({
Key key,
this.controller, // 控制正在編輯文本
this.focusNode, // 擷取鍵盤焦點
this.decoration = const InputDecoration(), // 邊框裝飾
TextInputType keyboardType, // 鍵盤類型
this.textInputAction, // 鍵盤的操作按鈕類型
this.textCapitalization = TextCapitalization.none, // 配置大小寫鍵盤
this.style, // 輸入文本樣式
this.textAlign = TextAlign.start, // 對齊方式
this.textDirection, // 文本方向
this.autofocus = false, // 是否自動對焦
this.obscureText = false, // 是否隐藏内容,例如密碼格式
this.autocorrect = true, // 是否自動校正
this.maxLines = 1, // 最大行數
this.maxLength, // 允許輸入的最大長度
this.maxLengthEnforced = true, // 是否允許超過輸入最大長度
this.onChanged, // 文本内容變更時回調
this.onEditingComplete, // 送出内容時回調
this.onSubmitted, // 使用者提示完成時回調
this.inputFormatters, // 驗證及格式
this.enabled, // 是否不可點選
this.cursorWidth = 2.0, // 光标寬度
this.cursorRadius, // 光标圓角弧度
this.cursorColor, // 光标顔色
this.keyboardAppearance, // 鍵盤亮度
this.scrollPadding = const EdgeInsets.all(20.0), // 滾動到視圖中時,填充邊距
this.enableInteractiveSelection, // 長按是否展示【剪切/複制/粘貼菜單LengthLimitingTextInputFormatter】
this.onTap, // 點選時回調
})
分析源碼可得,TextField 是有狀态 StatefulWidget,有豐富的屬性,自定義化較高,實踐中需要合理利用各種回調;
案例嘗試
- 小菜嘗試最基本的 TextField,區分預設狀态和擷取焦點狀态;
return TextField();

- 小菜嘗試了光标的相關屬性;cursorColor 為光标顔色,cursorWidth 為光标寬度,cursorRadius 為光标圓角;其中 Radius 提供了 circle 圓角和 elliptical 非圓角兩種;
return TextField(cursorColor: Colors.purple.withOpacity(0.4), cursorWidth: 10.0, cursorRadius: Radius.circular(4.0));
- textAlign 為文字起始位置,可根據業務光标居左/居右/居中等;注意隻是文字開始方向;textDirection 問文字内容方向,從左向右或從右向左;
return TextField(style: TextStyle(color: Colors.purple.withOpacity(0.7), fontSize: 18.0), textAlign: TextAlign.right);
- maxLength 為字元長度,設定時預設是展示一行,且右下角有編輯長度與整體長度對比;與 maxLengthEnforced 配合,maxLengthEnforced 為 true 時達到最大字元長度後不可編輯;為 false 時可繼續編輯展示有差别;
return TextField(maxLength: 30, maxLengthEnforced: true);
return TextField(maxLength: 30, maxLengthEnforced: false);
- 設定 maxLength 之後右下角預設有字元計數器,設定 TextField.noMaxLength 即可隻展示輸入字元數;
return TextField(maxLength: TextField.noMaxLength);
- maxLines 為允許展現的最大行數,在使用 maxLength 時内容超過一行不會自動換行,因為預設 maxLines=1,此時設定為 null 或固定展示行數即可自動換行;差別在于 null 會展示多行,而 maxLines 最多隻展示到設定行數;
return TextField(maxLength: 130, maxLengthEnforced: false, maxLines: null);
return TextField(maxLength: 130, maxLengthEnforced: false, maxLines: 2);
- obscureText 是否隐藏編輯内容,常見的密碼格式;
return TextField(obscureText: true);
- enableInteractiveSelection 長按是否出現【剪切/複制/粘貼】菜單;不可為空;
return TextField(enableInteractiveSelection: false);
- keyboardAppearance 為鍵盤亮度,包括 Brightness.dark/light 兩種,但僅限于 iOS 裝置;
return TextField(keyboardAppearance: Brightness.dark);
- textCapitalization 文字大小寫;理論上 sentences 為每句話第一個字母大寫;characters 為每個字母大寫;words 為每個單詞首字母大寫;但該屬性僅限于 text keybord,小菜在本地更換多種方式并未實作,有待研究;
return TextField(textCapitalization: TextCapitalization.sentences);
- keyboardType 為鍵盤類型,小菜了解整體分為數字鍵盤和字母鍵盤等;根據設定的鍵盤類型,鍵盤會有差别;
-
數字鍵盤
--1-- datetime 鍵盤上可随時通路 : 和 /;
--2-- phone 鍵盤上可随時通路 # 和 *;
--3-- number 鍵盤上可随時通路 + - * /
-
字母鍵盤
--1-- emailAddress 鍵盤上可随時通路 @ 和 .;
--2-- url 鍵盤上可随時通路 / 和 .;
--3-- multiline 适用于多行文本換行;
--4-- text 預設字母鍵盤;
return TextField(keyboardType: TextInputType.number);
return TextField(keyboardType: TextInputType.emailAddress);
- textInputAction 通常為鍵盤右下角操作類型,小菜以前稍微整理過,類型衆多,建議多多嘗試;
return TextField(textInputAction: TextInputAction.search);
- autofocus 是否自動擷取焦點,進入頁面優先擷取焦點,并彈出鍵盤,若頁面中有多個 TextField 設定 autofocus 為 true 則優先擷取第一個焦點;
return TextField(autofocus: true);
- focusNode 手動擷取焦點,可配合鍵盤輸入等減少使用者操作次數,直接擷取下一個 TextField 焦點;
FocusScope.of(context).requestFocus(node);
return TextField(focusNode: node);
- enabled 設為 false 之後 TextField 為不可編輯狀态;
return TextField(enabled: false);
- decoration 為邊框修飾,可以借此來調整 TextField 展示效果;可以設定前置圖示,後置圖檔,邊框屬性,内容屬性等,小菜會在後續集中嘗試;若要完全删除裝飾,将 decoration 設定為空即可;
return TextField(decoration: InputDecoration(icon: Icon(Icons.android)));
- inputFormatters 為格式驗證,例如原生 Android 中通常會限制輸入手機号或其他特殊字元,在 Flutter 中也可以借此來進行格式限制,包括正規表達式;使用時需要引入 package:flutter/services.dart;
- LengthLimitingTextInputFormatter 限制最長字元;
- WhitelistingTextInputFormatter 僅允許輸入白名單中字元;如 digitsOnly 僅支援數字 [0-9];
- BlacklistingTextInputFormatter 防止輸入黑名單中字元;如 singleLineFormatter 強制輸入單行;分析源碼 RegExp("[/\]") 可以設定正規表達式;
return TextField(inputFormatters: <TextInputFormatter>[
LengthLimitingTextInputFormatter(12),
WhitelistingTextInputFormatter.digitsOnly,
BlacklistingTextInputFormatter.singleLineFormatter
]);
- onChanged 文本内容變更時回調,可實時監聽 TextField 輸入内容;
Center(child: Text(_textStr))
return TextField(onChanged: (text) {
setState(() {
_textStr = text;
});
});
- controller 文本控制器,監聽輸入内容回調;
TextEditingController controller = TextEditingController();
@override
void initState() {
super.initState();
controller.addListener(() {
setState(() {
_textStr = controller.text;
});
});
}
return TextField(controller: controller);
- onTap 點選 TextField時回調;
return TextField(
onTap: () {
Toast.show('onTap!', context, duration: Toast.LENGTH_SHORT, gravity: Toast.TOP);
},
);
- onEditingComplete 在送出内容時回調,通常是點選回車按鍵時回調;
return TextField(
onEditingComplete: () {
Toast.show('onEditingComplete!', context, duration: Toast.LENGTH_SHORT, gravity: Toast.CENTER);
},
);
- onSubmit 在送出時回調,不可與 onEditingComplete 同時使用,差別在于 onSubmit 是帶傳回值的回調;
return TextField(
onEditingComplete: () {
Toast.show('onSubmitted -> $text!', context, duration: Toast.LENGTH_SHORT, gravity: Toast.CENTER);
},
);
問題小結
1. 鍵盤彈出會把輸入框或其它元件頂上去?
當 TextField 擷取焦點彈出輸入框時,輸入框可能會将頁面中元素頂上去,為避免此情況,可将 Scaffold 中 resizeToAvoidBottomPadding: false 即可,resizeToAvoidBottomPadding 設定是否自動調整body屬性控件的大小,以避免 Scaffold 底部被覆寫;
resizeToAvoidBottomPadding: false
resizeToAvoidBottomPadding: true
2. 長按輸入框出現【剪切/複制/粘貼】的菜單如何設定中文?
當 TextField 設定 enableInteractiveSelection 屬性後長按會出現菜單,預設為英文,可通過設定 Flutter 國際化來處理;
- 在 pubspec.yaml 中內建 flutter_localizations;
dependencies:
flutter:
sdk: flutter
flutter_localizations:
sdk: flutter
- 在 MaterialApp 中設定本地化代理和支援的語言類型;
return MaterialApp(
localizationsDelegates: [
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
],
supportedLocales: [
const Locale('zh', 'CN'),
const Locale('en', 'US'),
]
}
3. 使用 maxLength 時如何取消文本框右下角字元計數器?
- 将 maxLength 設定為 null 僅使用 LengthLimitingTextInputFormatter 限制最長字元;
return TextField(maxLength: null, inputFormatters: <TextInputFormatter>[
LengthLimitingTextInputFormatter(10)
]);
- 設定 InputDecoration 中 ** 屬性為空;但是底部有空餘,隻是隐藏而并非消失;
return TextField(decoration: InputDecoration(counterText: ""), maxLength: 10);
文本框是日常開發中必不可少的元件,小菜還在探索過程中,如有問題請多多指導!
來源: 阿策小和尚