truncate function

String truncate(
  1. String text,
  2. int width
)

Truncates text to width characters, adding an ellipsis if clipped.

If text fits within width, it's returned unchanged. If truncation is needed, the last character becomes '…'.

Example:

truncate('Hello World', 8); // 'Hello W…'
truncate('Hi', 10); // 'Hi'

Implementation

String truncate(String text, int width) {
  if (text.length <= width) return text;
  if (width <= 1) return text.substring(0, width);
  return '${text.substring(0, width - 1)}…';
}