TextField controlled controller.addListener(() gets called multiple time after using the controller.clear
131
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;
});
}
});
}
Author by
Masoud H
Updated on November 28, 2022Comments
-
Masoud H over 1 year
The method
addListener()
of the TextEditingController get called multiple times after executing theclear()
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?