[英]Managing events in flutter's TextFormField
在Flutter項目中,我需要收聽TextFormField中的輸入文本並執行某些操作,尤其是當用戶在此字段中放置某個字符(例如空格)或請求焦點時。 當這種事件發生時,我需要修改字段的值。 我知道有一個called controller
的屬性,但在這種情況下我不知道如何使用它。
先感謝您。
您可以指定控制器和焦點節點,然后向其添加偵聽器以監視更改。
例如:
定義控制器和焦點節點
TextEditingController _controller = new TextEditingController();
FocusNode _textFocus = new FocusNode();
定義監聽器功能
void onChange(){
String text = _controller.text;
bool hasFocus = _textFocus.hasFocus;
//do your text transforming
_controller.text = newText;
_controller.selection = new TextSelection(
baseOffset: newText.length,
extentOffset: newText.length
);
}
將listner添加到控制器,並將focusnode添加到initState
// you can have different listner functions if you wish
_controller.addListener(onChange);
_textFocus.addListener(onChange);
然后你可以用它
new TextFormField(
controller: _controller,
focusNode: _textFocus,
)
希望有所幫助!
如果您只是嘗試將輸入轉換為TextFormField中的其他形式,則最好使用“TextInputFormatter”。 使用帶有TextController的監聽器會導致很多麻煩。 看看我的示例代碼,看看是否對您有所幫助。 順便說一句,最后一行代碼只是試圖將光標移動到文本的末尾。
TextFormField(inputFormatters: [QuantityInputFormatter()])
class QuantityInputFormatter extends TextInputFormatter {
@override
TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
final intStr = (int.tryParse(newValue.text) ?? 0).toString();
return TextEditingValue(
text: intStr, selection: TextSelection.collapsed(offset: intStr.length),);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.