本文介绍了在Flutter的TextFormField中管理事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Flutter项目中,我需要听取TextFormField中的输入文本并执行某些操作,尤其是当用户在此文件中放置一些字符(例如空格)或请求焦点时.当发生此类事件时,我需要修改字段的值.我知道有一个属性called controller
,但在这种情况下我不知道如何使用它.
In Flutter project, I need to listen to the input text in TextFormField and do certain actions, especially when user put some character (eg. space) in this filed or when he request focus. When this kind of event happen, I need to modify filed's value.I know there is a property called controller
but I don't know how to use it in this case.
谢谢.
推荐答案
您可以指定一个控制器和焦点节点,然后向其添加侦听器以监视更改.
You can specify a controller and focus node, then add listeners to them to monitor for changes.
例如:
定义控制器和焦点节点
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,
)
希望有帮助!
这篇关于在Flutter的TextFormField中管理事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!