truncate static method

TextEditingValue truncate(
  1. TextEditingValue value,
  2. int maxLength
)

Truncate the given TextEditingValue to maxLength using String.length (not user-perceived characters).

See also:

Implementation

static TextEditingValue truncate(TextEditingValue value, int maxLength) {
  //
  // If the text fits the available space, use it all.
  if (value.text.length <= maxLength)
    return value;
  //
  // If the text doesn't fit the available space, we must cut it,
  // but do not cut a grapheme in half.
  else {
    String truncated = truncateString(value.text, maxLength);

    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,
    );
  }
}