TextField controlled controller.addListener(() gets called multiple time after using the controller.clear

Viewed 283

The method addListener() of the TextEditingController get called multiple times after executing the clear() method, this will only happen if we are clearing it.

TextEditingController _pinPutController = TextEditingController();
  @override
  void initState() {
    _pinPutController.addListener(() {
      if (_pinPutController.text.length > 4) {
          print("Hello world");
          _pinPutController.clear();
      }
  });
} 

When the condition in the if statement is true, the body is executed twice.

Can anyone help me to solve this problem?

1 Answers
bool isClear = false;

TextField(
  controller: _pinPutController,
  decoration: InputDecoration(
    hintText: "Enter a message",
    suffixIcon: IconButton(
      onPressed: () => (isClear)?_pinPutController.clear(): null,
      icon: Icon(Icons.clear),
    ),
  ),
)

Change the code you wrote by adding isClear into it

TextEditingController _pinPutController = TextEditingController();
  @override
  void initState() {
    _pinPutController.addListener(() {
      if (_pinPutController.text.length > 4) {
          setState(() {
            isClear = true;
          });
      }
  });
}
Related