Want to use NumberFormat in TextInputFormatter in Flutter? This is because after you format the value you are adding a new char but the the text selection remains at the same position, one char less, this cause an expected behavior
You can modified your TextInputFormatter like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
class NumericTextFormatter extends TextInputFormatter { TextEditingValue formatEditUpdate( TextEditingValue oldValue, TextEditingValue newValue) { if (newValue.text.length == 0) { return newValue.copyWith(text: ''); } else if (newValue.text.compareTo(oldValue.text) != 0) { int selectionIndexFromTheRight = newValue.text.length - newValue.selection.end; final f = new NumberFormat("#,###"); int num = int.parse(newValue.text.replaceAll(f.symbols.GROUP_SEP, '')); final newString = f.format(num); return new TextEditingValue( text: newString, selection: TextSelection.collapsed(offset: newString.length - selectionIndexFromTheRight), ); } else { return newValue; } } } |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.