truncate method

String truncate(
  1. int maxLength, {
  2. String suffix = '…',
})

Truncates this string to at most maxLength characters.

If the string exceeds maxLength, it is cut and suffix is appended (defaults to "…"). The returned string's total length will be at most maxLength (suffix length is counted).

If maxLength is less than or equal to suffix's length, only the suffix is returned.

'Hello World'.truncate(8);           // "Hello W…"
'Hello World'.truncate(12);          // "Hello World" (no change)
'Hello World'.truncate(8, '...');    // "Hello..."

Implementation

String truncate(int maxLength, {String suffix = '…'}) {
  if (length <= maxLength) return this;
  if (maxLength <= suffix.length) return suffix;
  return '${substring(0, maxLength - suffix.length)}$suffix';
}