在Flutter 项目中,我需要收听TextFormField中的输入文本并执行某些操作,特别是当用户输入某些字符(例如.空间),或者当他请求焦点时.当这种事件发生时,我需要修改字段的值.
我知道有called controller
元,但我不知道在这种情况下怎么用.
提前谢谢你.
在Flutter 项目中,我需要收听TextFormField中的输入文本并执行某些操作,特别是当用户输入某些字符(例如.空间),或者当他请求焦点时.当这种事件发生时,我需要修改字段的值.
我知道有called controller
元,但我不知道在这种情况下怎么用.
提前谢谢你.
您可以指定控制器和焦点 node ,然后向它们添加侦听器以监视更改.
例如:
定义控制器和焦点 node
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添加到控制器,并将焦点 node 设置为initState
// you can have different listner functions if you wish
_controller.addListener(onChange);
_textFocus.addListener(onChange);
然后您可以将其用作
new TextFormField(
controller: _controller,
focusNode: _textFocus,
)
希望这会有帮助!