I'm trying to use NumberFromatter
in TextInputFormatter
but when I try to use it, it completely messed up! This is my TextInputFormatter
implementation code:
class NumericTextFormatter extends TextInputFormatter {
TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
if(newValue.text.length > 0) {
int num = int.parse(newValue.text.replaceAll(',', ''));
final f = new NumberFormat("#,###");
return newValue.copyWith(text: f.format(num));
} else {
return newValue.copyWith(text: '');
}
}
}
So when I add this formatter to a TextField
and try to type 1 to 9, what I expect to see is something like: 123,456,789
But this is what shows in TextField
:
1
12
123
1,234
12,354 <- this is where it starts
123,564
1,235,674
12,356,874 <- and it happends again
It seems that cursor moves after adding one , character. So can anyone helps me with this?
The custom TextInputFormatter But sometimes, you need to create your own formatter for a specific task. We can create a custom TextInputFormatter by extending the TextInput Formatter and implementing the formatEditUpdate method, which accepts two parameters of type TextEditingValue: oldValue and old newValue.
The TextField widget is required to set keyboardType: TextInputType. number, and inputFormatters: <TextInputFormatter>[FilteringTextInputFormatter. digitsOnly] to accept numbers only as input.
Flutter does not provide a predefined input for numbers. However, we can use the capabilities of a TextField (or TextFormField ) to mimic the behavior we want a number input to have. It's as simple as changing the keyboard to one that only provides numbers and the allowed characters to digits only.
onChanged: (val) { RegExp comma = new RegExp(r"(?!,\n),+|,\n,"); if (comma. hasMatch(val)) { final newVal = val. replaceAll(comma, ",\n"); _roomIdController. text = newVal; _roomIdController.
This is because after you format the value you are adding a new char but the text selection remains at the same position, one char less, this cause an expected behavior
You can modify your TextInputFormatter
like this:
Fixed to support all locales and to remember cursor position
class NumericTextFormatter extends TextInputFormatter {
@override
TextEditingValue formatEditUpdate(
TextEditingValue oldValue, TextEditingValue newValue) {
if (newValue.text.isEmpty) {
return newValue.copyWith(text: '');
} else if (newValue.text.compareTo(oldValue.text) != 0) {
final int selectionIndexFromTheRight =
newValue.text.length - newValue.selection.end;
final f = NumberFormat("#,###");
final number =
int.parse(newValue.text.replaceAll(f.symbols.GROUP_SEP, ''));
final newString = f.format(number);
return TextEditingValue(
text: newString,
selection: TextSelection.collapsed(
offset: newString.length - selectionIndexFromTheRight),
);
} else {
return newValue;
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With