TextField元件在我們日常開發中很常用,下面就來總結一下它的用法。
從 TextField 中檢索資訊
1.第一種方法是使用 onChanged 方法並將當前值儲存在一個簡單的變數中。
String value = "";
TextField(
onChanged: (text) {
value = text;
},
)
複製程式碼
2.第二種方法是使用 TextEditingController。控制器附加到 TextField 上,讓我們監聽和控制 TextField 的文字。
TextEditingController controller = TextEditingController();
TextField(
controller: controller,
)
print(controller.text);//輸出當前TextField的值
複製程式碼
TextField 的其他回撥
///這些是在使用者單擊 iOS 上的“完成”按鈕時呼叫的回撥
onEditingComplete: () {},
onSubmitted: (value) {},
複製程式碼
在 TextFields 中使用焦點
1.使用自動對焦
TextField(
autofocus: true,
)
複製程式碼
2.改變自定義焦點

///點選RaisedButton時可以切換下一個TextField
FocusNode nodeOne = FocusNode();
FocusNode nodeTwo = FocusNode();
TextField(
focusNode: nodeOne,
),
TextField(
focusNode: nodeTwo,
),
RaisedButton(
onPressed: () {
FocusScope.of(context).requestFocus(nodeTwo);
},
child: Text("Next Field"),
)
複製程式碼
更改 TextFields 的鍵盤屬性
1.鍵盤型別
TextInputType.text (普通完整鍵盤)
TextInputType.number (數字鍵盤)
TextInputType.emailAddress (帶有“@”的普通鍵盤)
TextInputType.datetime (帶有“/”和“ : ”的數字鍵盤)
TextInputType.numberWithOptions (帶有啟用簽名和十進位制模式選項的數字鍵盤)
TextInputType.multiline (優化多行資訊)
TextField(
keyboardType: TextInputType.number,
)
複製程式碼
2.更改鍵盤本身的操作按鈕


///這會導致“完成”按鈕被“繼續”按鈕取代
TextField(
textInputAction: TextInputAction.continueAction,
)
///這會導致“完成”按鈕被“傳送”按鈕取代
TextField(
textInputAction: TextInputAction.send,
)
複製程式碼
3.自動更正
TextField(
autocorrect: false,
)
複製程式碼
4.文字大寫



TextCapitalization.sentences ///每個句子的首字母都被大寫
TextCapitalization.characters ///句子中的所有字元都大寫
TextCapitalization.words ///每個單詞的首字母大寫
TextField(
textCapitalization: TextCapitalization.sentences,
)
複製程式碼
文字樣式、對齊方式和游標選項
1.文字欄位中的文字對齊方式

///這將導致游標和文字在 TextField 中間開始
TextField(
textAlign: TextAlign.center,
)
複製程式碼
2.在 TextField 中設定文字的樣式
///style 屬性用來更改 TextField 中文字的外觀、顏色、字型大小等。
TextField(
style: TextStyle(color: Colors.red, fontWeight: FontWeight.w300),
)
複製程式碼
3.更改 TextField 中的游標

///更改游標顏色,寬度和角的半徑,這裡製作了一個紅色的圓形游標
TextField(
cursorColor: Colors.red,
cursorRadius: Radius.circular(16.0),
cursorWidth: 16.0,
)
複製程式碼
控制 TextField 中的大小和最大長度
1.控制最大字元數
TextField(
maxLength: 4,
)
複製程式碼
1.控制最大行數
TextField(
maxLines: 3,
)
複製程式碼
模糊文字

TextField(
obscureText: true,
)
複製程式碼
裝飾 TextField
1.使用提示
TextField(
decoration: InputDecoration(
hintText: "Demo Text",
hintStyle: TextStyle(fontWeight: FontWeight.w300, color: Colors.red)
),
)
複製程式碼
2.增加圖示

TextField(
decoration: InputDecoration(
prefixIcon: Icon(Icons.print)
),
)
複製程式碼

TextField(
decoration: InputDecoration(
icon: Icon(Icons.print)
),
)
複製程式碼

TextField(
decoration: InputDecoration(
prefix: CircularProgressIndicator(),
),
)
複製程式碼
3.去除游標
TextField(
decoration: InputDecoration.collapsed(hintText: "")
)
複製程式碼
4.增加邊框

TextField(
decoration: InputDecoration(
border: OutlineInputBorder()
)
)
複製程式碼
5.持久訊息

TextField(
decoration: InputDecoration(
border: OutlineInputBorder()
)
)
複製程式碼