Reputation: 73
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;
}
Upvotes: 2
Views: 3413
Reputation: 73
After a lot of struggle, I figured out that when we change the amountController.text
, the cursor moves to the beginning of the text, and therefore, you can't edit the textField
's value nor it updates on changes. So, you had to reposition the cursor to the end of string manually:
onChanged: (value) {
controller1.text = replaceFarsiNumber(value);
//reposition the cursor to the end of string
controller1.selection =
TextSelection.fromPosition(
TextPosition(offset: value.length));
},
Upvotes: 2
Reputation: 142
your code seems correct, to double check I tried your code and it runs correctly. Here is the output:
There may be another reason of your problem...
Upvotes: 1
Reputation: 23164
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;
}
},
Upvotes: 0