collapseMultilineString method

  1. @useResult
String collapseMultilineString({
  1. required int cropLength,
  2. bool appendEllipsis = true,
})

Returns this multiline string collapsed into a single line, truncated to cropLength characters (grapheme clusters).

When appendEllipsis is true (default), an ellipsis is appended if truncated. Emoji and combining marks count as one character each. Audited: 2026-06-12 11:26 EDT

Implementation

@useResult
String collapseMultilineString({
  required int cropLength,
  bool appendEllipsis = true,
}) {
  if (isEmpty) {
    return this;
  }

  final String collapsed = replaceAll(StringExtensions.newLine, ' ').replaceAll('  ', ' ');
  // Count and cut by grapheme throughout. The old loop shortened with
  // substringSafe(0, length - 1), mixing a code-unit length with a grapheme
  // index: with an emoji present nothing was removed, so it never ended.
  if (collapsed.characters.length <= cropLength) {
    return collapsed.trim();
  }

  Characters cropped = collapsed.characters.take(cropLength + 1);
  // ignore: unused_result -- false positive: result is consumed by the while test
  while (cropped.isNotEmpty && !cropped.string.endsWithAny(StringExtensions.commonWordEndings)) {
    cropped = cropped.skipLast(1);
  }

  // Drop the word-ending character itself, then tidy whitespace.
  final String result = cropped.isEmpty ? '' : cropped.skipLast(1).string.trim();

  return appendEllipsis ? result + StringExtensions.ellipsis : result;
}