truncate method

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

Truncates the string to the specified length with optional ellipsis.

If the string is shorter than maxLength, returns the original string.

Example:

'Hello World'.truncate(5); // 'Hello...'
'Hi'.truncate(5); // 'Hi'

Implementation

String truncate(int maxLength, {String ellipsis = '...'}) {
  assert(maxLength >= 0, 'maxLength must be non-negative');
  if (length <= maxLength) return this;
  return '${substring(0, maxLength)}$ellipsis';
}