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,
) {
  var text = newValue.text;

  // Clean text
  text = text.replaceAll(
    RegExp(r"[^0-9]"),
    '',
  );

  // Remove initial zero
  text = text.replaceFirst(
    RegExp(r'0*'),
    '',
  );

  // Add the zeros until you get to the whole part
  if (text.length <= mantissaLength)
    text = text.padLeft(
      mantissaLength + 1,
      '0',
    );

  if (text.length > mantissaLength) {
    final separatorOffset = text.length - mantissaLength;

    var integerPart = text.substring(
      0,
      separatorOffset,
    );
    final decimalPart = text.substring(
      separatorOffset,
      text.length,
    );

    if (thousandsSeparator != null) {
      integerPart = insertThousandSeparator(
        integerPart,
        thousandsSeparator!.char,
      );
    }

    text = '$integerPart${decimalSeparator.char}$decimalPart';

    return newValue.copyWith(
      selection: TextSelection.collapsed(
        offset: text.length,
      ),
      text: text,
    );
  }

  return newValue.copyWith(
    selection: TextSelection.collapsed(
      offset: text.length,
    ),
    text: text,
  );
}