16

I have a TextField that has a controller that has a listener for changes. Like this:

final TextEditingController _oneController = TextEditingController();
  @override
  void initState() {
    super.initState();
    _oneController.addListener(_listener);
  }
TextField(
  controller: _oneController,
),

Where _listener is a function that will dispatch an event that my form has been edited.

This works fine, but whenever you focus on the TextField it triggers this listener to run, even if no changes were made to the text in the field.

Is there a way to stop my listener from being called when the TextField enters focus? I don't want my listener to be called when there are no changes made to the text in my TextField.

5
  • Why don't just remove the listener ? Commented Jun 18, 2019 at 3:43
  • 2
    this is done on purpose and you cannot avoid it - you have to make some checks inside your _listener - but if you used streams/rxdart you could do that by adding simple distinct() method Commented Jun 18, 2019 at 3:47
  • 4
    the listener will trigger when it's focused. if you want to trigger something only upon a change in the text field use onChanged. Commented Jun 18, 2019 at 4:43
  • Same thing here, oddly enough the listener is periodically triggered, even if no data is entered. Using TextField.onChanged() isn't a workaround neither, as it causes all kind of weird text behavior. Commented Apr 14, 2020 at 11:07
  • 2
    This is because the value of TextEditingController is not String but TextEditingValue. In addition to text, it contains selection info and some more data. So the value might actually change even when text has not changed. This is the reason why the listener is called on focus. This is also why you are accessing the text using .text and not .value as you normally do with ValueNotifier. Commented Jun 16, 2022 at 15:19

1 Answer 1

11

Store the previously typed text in a variable called prev. (initially prev = ""). everytime _listener gets called, check if the _oneController.text == prev, if they both are same, no need to call the function. execute the function _listener if the prev is not as same as the text.

_listener(){
    if(prev != _oneController.text){
         prev = _oneController.text;
         //your rest of the code, whatever u wanna do.
     }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.