truncateText function

String truncateText(
  1. String text,
  2. int limit, {
  3. bool wholeWords = false,
  4. bool addDots = false,
  5. bool addSpaceDots = false,
})

Truncate text for limit, optionally find nearest whitespace for whole words

Implementation

String truncateText(
  String text,
  int limit, {
  bool wholeWords = false,
  bool addDots = false,
  bool addSpaceDots = false,
}) {
  if (text.length > limit) {
    if (wholeWords && text.contains(' ')) {
      final String part = text.substring(0, limit);
      final int whitespace = part.lastIndexOf(' ');

      return part.substring(0, whitespace) +
          (addDots ? (addSpaceDots ? ' ...' : '...') : '');
    } else {
      return text.substring(0, limit) +
          (addDots ? (addSpaceDots ? ' ...' : '...') : '');
    }
  }

  return text;
}