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) {
  if (newValue.text == _last) {
    return oldValue;
  }
  if (newValue.text.isEmpty) {
    if (null is! T) {
      _last = '0';
      return TextEditingValue(
          text: _last, selection: const TextSelection.collapsed(offset: 1));
    } else {
      _last = newValue.text;
      return newValue;
    }
  }

  var text = newValue.text.replaceAll(_thousand, '');
  if (_decimal != '.') {
    text = text.replaceAll(_decimal, '.');
  }
  if (!_regex.hasMatch(text)) {
    return oldValue;
  }

  //convert to number
  num number = 0;
  switch (_type) {
    case 'int':
    case 'int?':
      number = int.tryParse(text) ?? 0;
      break;
    case 'double':
    case 'double?':
      number = double.tryParse(text) ?? 0;
      break;
    default:
      throw UnimplementedError();
  }
  text = numberFormat.format(number).trim();
  if (newValue.text.endsWith(_decimal) && !text.contains(_decimal)) {
    text += _decimal;
  }

  //current cursor
  final m = RegExp('[\\d\\$_decimal]');
  var old = 0;
  for (var i = 0; i < newValue.selection.end; i++) {
    if (m.hasMatch(newValue.text[i])) {
      old++;
    }
  }

  var ind = 0;
  var cur = 0;
  for (var i = 0; i < text.length && ind < old; i++) {
    if (m.hasMatch(text[i])) ind++;
    cur++;
  }

  _last = text;
  return TextEditingValue(
    text: text,
    selection: TextSelection.collapsed(offset: cur),
  );
}