collapseMultilineString method

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

Collapses a multiline string into a single line with optional truncation.

Implementation

String collapseMultilineString({required int cropLength, bool appendEllipsis = true}) {
  if (isEmpty) return this;
  final String collapsed = replaceAll(newLine, ' ').replaceAll('  ', ' ');
  if (collapsed.length <= cropLength) return collapsed.trim();

  String cropped = collapsed.substringSafe(0, cropLength + 1);
  while (cropped.isNotEmpty && !cropped.endsWithAny(commonWordEndings)) {
    cropped = cropped.substringSafe(0, cropped.length - 1);
  }
  if (cropped.isNotEmpty) {
    cropped = cropped.substringSafe(0, cropped.length - 1).trim();
  }
  return appendEllipsis ? cropped + ellipsis : cropped;
}