Flutter: how to use .addListener of TextEditingController

Viewed 4492

i'm building a simple app that prints the result of the current TextFormField. Such as when the text changes it prints the new value.

I found out that you can achieve this with TextEditingController.addListener that listens for changes and executes a function.

So i wrapped it all in initState as follows

@override
  void initState() {
      addressController.addListener(() {
        print(addressController.text);
      });

The problem I have is that sometimes it records changes even when there aren't any:

This is what happens writing a word and then deleting it.

enter code here

1 Answers

If you add listener then you should remove it somewhere, otherwise there can be situation when TextEditingController will have 2 or more listeners:

@override
void initState() {
    addressController.addListener(_addressControllerListener); 
    super.initState() 
}

void _addressControllerListener() {    
    print(addressController.text); 
}

@override 
void dispose() { 
   addressController.removeListener(_addressControllerListener); 
   super.dispose() 
}
Related