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, // unused.
  TextEditingValue newValue,
) {
  // This does not count grapheme clusters (i.e. characters visible to the user),
  // it counts Unicode runes, which leaves out a number of useful possible
  // characters (like many emoji), so this will be inaccurate in the
  // presence of those characters. The Dart lang bug
  // https://github.com/dart-lang/sdk/issues/28404 has been filed to
  // address this in Dart.
  // TODO(justinmc): convert this to count actual characters using Dart's
  // characters package (https://pub.dev/packages/characters).
  if (maxLength != null && maxLength > 0 && newValue.text.runes.length > maxLength) {
    // If already at the maximum and tried to enter even more, keep the old
    // value.
    if (oldValue.text.runes.length == maxLength) {
      return oldValue;
    }
    return truncate(newValue, maxLength);
  }
  return newValue;
}