Managing events in flutter's TextFormField

2019-02-14 04:55发布

问题:

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.

回答1:

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!