truncate static method

String truncate(
  1. String str, [
  2. int threshold = 100
])

Truncate string

Truncates the string to the specified threshold, adding "..." if the string is longer than the threshold.

threshold is the maximum length of the string to return. If the string is longer than this, it will be truncated.

Throws InvalidArgumentException if threshold is less than or equal to 0.

Returns the truncated string if it is longer than the threshold, otherwise returns the original string.

Implementation

static String truncate(String str, [int threshold = 100]) {
  if (threshold <= 0) throw InvalidArgumentException('Truncation threshold must be positive: $threshold');
  if (str.length > threshold) {
    return '${str.substring(0, threshold)} (truncated)...';
  }
  return str;
}