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,
) {
  assert(
    min == null ||
        max == null ||
        !stepStrictly ||
        (min! % step == 0 && max! % step == 0),
    '当严格步进时,min 和 max 都应是 step 的整数倍',
  );

  String text = newValue.text;

  // 允许空输入
  if (text.isEmpty) {
    return newValue;
  }

  // 允许输入负号或小数点(作为输入中间状态)
  if (text == '-' || text == '.' || text == '-.') {
    // 检查是否允许负数
    if (text.startsWith('-') && min != null && min! >= 0) {
      return oldValue; // 不允许负数
    }
    return newValue;
  }

  final num? value = num.tryParse(text);
  if (value == null) {
    return const TextEditingValue();
  }

  if (min != null && value < min!) {
    return oldValue;
  }

  if (max != null && value > max!) {
    return oldValue;
  }

  if (stepStrictly && value % step != 0) {
    text = ((value ~/ step) * step).toString();
  }

  if (precision != null && text.contains('.')) {
    final list = text.split('.');
    final int decimalLength = list.last.length;
    final int integerLength = list.first.length;
    if (decimalLength > precision!) {
      text = text.substring(0, integerLength + 1 + precision!);
    }
  }

  return TextEditingValue(
    text: text,
    selection: newValue.selection.copyWith(
      baseOffset: math.min(newValue.selection.start, text.length),
      extentOffset: math.min(newValue.selection.end, text.length),
    ),
    composing: !newValue.composing.isCollapsed &&
            text.length > newValue.composing.start
        ? TextRange(
            start: newValue.composing.start,
            end: math.min(newValue.composing.end, text.length),
          )
        : TextRange.empty,
  );
}