truncate method Null safety

  1. @visibleForTesting
TextEditingValue truncate(
  1. TextEditingValue value,
  2. int maxLength
)
visibleForTesting">@visibleForTesting

Truncate the given TextEditingValue to maxLength user-perceived characters.

See also:

Implementation

@visibleForTesting
static TextEditingValue truncate(TextEditingValue value, int maxLength) {
  final CharacterRange iterator = CharacterRange(value.text);
  if (value.text.characters.length > maxLength) {
    iterator.expandNext(maxLength);
  }
  final String truncated = iterator.current;

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