formatEditUpdate method

  1. @override
TextEditingValue formatEditUpdate(
  1. TextEditingValue oldValue,
  2. TextEditingValue newValue
)
override

Called when text is being typed or cut/copy/pasted in the EditableText.

You can override the resulting text based on the previous text value and the incoming new text value.

When formatters are chained, oldValue reflects the initial value of TextEditingValue at the beginning of the chain.

Implementation

@override
TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {

  final int newBaseOffset = newValue.selection.baseOffset;
  final String newtext = newValue.text;
  final String text = newtext.replaceAll(RegExp('[^0-9]'), '');

  if (newBaseOffset > maxDigits) {
    return oldValue;
  }

  final currency = NumberFormat.currency(locale: locale, symbol: symbol, decimalDigits: decimalDigits);

  num _newNum = num.tryParse(newValue.text) ?? 0;

  if (currency.decimalDigits! > 0) {
    _newNum /= pow(10, currency.decimalDigits!);
  }
  final _newString = currency.format(_newNum).trim();

  if (text.trim() == '' || text == '00' || text == '000') {
    return TextEditingValue(text: '', selection: TextSelection.collapsed(offset: 0));
  }

  return TextEditingValue(text: _newString, selection: TextSelection.collapsed(offset: _newString.length));
}