Managing events in flutter's TextFormField

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 are just trying to transform the input to other form in TextFormField, you better use "TextInputFormatter". Using a listener with TextController cause a lot of troubles. Take a look at my sample code see if that helps you. btw, The last line of code is just trying to move the cursor to the end of text.

TextFormField(inputFormatters: [QuantityInputFormatter()])

class QuantityInputFormatter extends TextInputFormatter {
  @override
  TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
    final intStr = (int.tryParse(newValue.text) ?? 0).toString();
    return TextEditingValue(
            text: intStr, selection: TextSelection.collapsed(offset: intStr.length),);
  }
}