Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Managing events in flutter's TextFormField

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.

like image 522
mynameis Avatar asked Feb 19 '18 16:02

mynameis


People also ask

What is the difference between TextField and TextFormField in Flutter?

The main difference between TextFormField and TextField is that the TextFormField widget uses the Form widget, which can contain multiple TextField widgets.


1 Answers

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!

like image 150
Hemanth Raj Avatar answered Sep 24 '22 06:09

Hemanth Raj