在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
);
}
在qazxsw poi中添加侦听器和focusnode的侦听器
initState
然后你可以用它
// you can have different listner functions if you wish
_controller.addListener(onChange);
_textFocus.addListener(onChange);
希望有所帮助!
如果您只是尝试将输入转换为TextFormField中的其他形式,则最好使用“TextInputFormatter”。使用带有TextController的监听器会导致很多麻烦。看看我的示例代码,看看是否对您有所帮助。顺便说一句,最后一行代码只是试图将光标移动到文本的末尾。
new TextFormField(
controller: _controller,
focusNode: _textFocus,
)