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.
Thank you in advance.
The main difference between TextFormField and TextField is that the TextFormField widget uses the Form widget, which can contain multiple TextField widgets.
You can specify a controller and focus node, then add listeners to them to monitor for changes.
Ex:
Define controllers and focus nodes
TextEditingController _controller = new TextEditingController();
FocusNode _textFocus = new FocusNode();
Define listener function
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
);
}
Add listner to controller and focusnode at initState
// you can have different listner functions if you wish
_controller.addListener(onChange);
_textFocus.addListener(onChange);
Then you can use it as
new TextFormField(
controller: _controller,
focusNode: _textFocus,
)
Hope that helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With