Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter TextEditingController listener being triggered when TextField is focused

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.

like image 435
alisonthemonster Avatar asked Jun 18 '19 02:06

alisonthemonster


Video Answer


1 Answers

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.
     }
}
like image 83
saurabh Avatar answered Sep 22 '22 07:09

saurabh