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.composing.isValid) {
    return newValue;
  }
  // 如果没有拼音输入,则检查最终文本的长度
  if (newValue.text.length > maxLength) {
    intercept?.call(maxLength);
    // 如果超出限制,则截断到最大长度
    return TextEditingValue(
      text: newValue.text.substring(0, maxLength),
      selection: TextSelection.collapsed(offset: maxLength),
    );
  }

  // 长度符合要求,直接返回
  return newValue;
}