ellipsize function

String ellipsize(
  1. String text, {
  2. required int maxLength,
  3. bool showEllipsisCount = true,
})

Shortens the text using an ellipsis if its number of characters exceeds maxLength.

If showEllipsisCount is true, then it shows the number of characters that were "ellipsized away" between parenthesis.

Example :

final text = 'This is a new text';

final ellipsized1 = _ellipsize(
  text,
  maxLength: 14,
  showEllipsisCount: false,
);
/// => 'This is a new…'

final ellipsized2 = _ellipsize(
  text,
  maxLength: 14,
  showEllipsisCount: true,
);
/// => 'This is … (+4)'

/// Notice how both strings are exactly 14 characters long.

NB : For a specific definition of what is considered a character, see the characters package on Pub.

Implementation

String ellipsize(
  String text, {
  required int maxLength,
  bool showEllipsisCount = true,
}) {
  assert(maxLength > 0);

  final characters = Characters(text);

  if (characters.length <= maxLength) {
    return characters.string;
  }

  if (!showEllipsisCount) {
    // The final string result should not exceed maxLength, so we take into
    // take into account the added '…' character
    final end = maxLength - 1;
    return '${characters.getRange(0, end).string}…';
  }

  final shownTextLength =
      _calculateShownTextLength(characters.length, maxLength);

  // The number of characters hidden by the ellipsis.
  final ellipsisCount = characters.length - shownTextLength;

  return '${characters.getRange(0, shownTextLength).string}… (+$ellipsisCount)';
}