在 flutter 的 TextFormField 中管理事件
Managing events in flutter's TextFormField
在 Flutter 项目中,我需要监听 TextFormField 中的输入文本并执行某些操作,尤其是当用户在此字段中输入某些字符(例如 space)或请求焦点时。当这种事件发生时,我需要修改 filed 的值。
我知道有一个 属性 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
);
}
在 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),);
}
}
在 Flutter 项目中,我需要监听 TextFormField 中的输入文本并执行某些操作,尤其是当用户在此字段中输入某些字符(例如 space)或请求焦点时。当这种事件发生时,我需要修改 filed 的值。
我知道有一个 属性 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
);
}
在 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),);
}
}