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 handlerValue = super.formatEditUpdate(oldValue, newValue);
  String value = handlerValue.text.replaceAll(',', '.');
  int selectionIndex = handlerValue.selection.end;

  ///如果输入框内容为.直接将输入框赋值为0.
  if (value == '.') {
    value = '0.';
    selectionIndex++;
  }

  ///判断小数位数
  if (_getValueDigit(value) > digit || _pointCount(value) > 1) {
    value = oldValue.text;
    selectionIndex = oldValue.text.length;
  }
  // 判断金额大小
  if ((double.tryParse(value) ?? 0) > max) {
    value = Decimal.parse(max.toString()).toString();
    selectionIndex = value.length;
  }
  return TextEditingValue(
    text: value,
    selection: TextSelection.collapsed(offset: selectionIndex),
  );
}