truncate method
Truncates the string to maxLength characters, optionally adding '...' at the end.
Returns the original string if it's already shorter than maxLength.
If ellipsis is true, the ellipsis does not count toward the maxLength.
Example:
'Hello World'.truncate(5) // 'Hello'
'Hello World'.truncate(5, ellipsis: true) // 'Hello...'
'Hi'.truncate(5) // 'Hi' (no change)
Implementation
String truncate(int maxLength, [bool ellipsis = false]) {
if (maxLength <= 0) {
return '';
}
if (length <= maxLength) {
return this;
};
return ellipsis ? '${substring(0, maxLength)}...' : substring(0, maxLength);
}