Home > Software design >  TextField's text does not update after changing its controller's text in onChanged field
TextField's text does not update after changing its controller's text in onChanged field

Time:04-21

I have a textfield with a controller. What I want to do is change the input characters as they are being received. But what happens is that it replaces the first entered character, but then, the controller's text does not update on changes afterwards. Actually, nothing happens when you press a key.

here is my textfield:

TextEditingController amountController = TextEditingController();
TextField(
  controller: amountController,
  onChanged: (value) {
  amountController.text = replaceFarsiNumber(value);
  },
)

Here is the replaceFarsiNumber() function for further information:

String replaceFarsiNumber(String input) {
  const english = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
  const farsi = ['۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹'];
  for (int i = 0; i < english.length; i  ) {
    input = input.replaceAll(english[i], farsi[i]);
  }
  return input;
}

CodePudding user response:

your code seems correct, to double check I tried your code and it runs correctly. Here is the output:

enter image description here

There may be another reason of your problem...

CodePudding user response:

I believe the problem is that it enters an infinite loop. onChanged changes the text which in turn triggers a new onChanged and this goes on infinitely. It might help to only assign to the text when the text is different. So like

onChanged: (value) {
  var newValue = replaceFarsiNumber(value);
  if (value != newValue) {
    amountController.text = newValue;
  }
},
  • Related