Dart: How to Truncate String and add Ellipsis after character number

Tayo.dev picture Tayo.dev · Nov 18, 2018 · Viewed 8.3k times · Source

I'd like to add Ellipsis to a string after a certain character length and if the string length is not up to the character preset character length, the ellipsis (...) Should NOT be added.

How do i achieve this in Dart Language?

Answer

Nick Meinhold picture Nick Meinhold · May 17, 2019

You could do something like this:

String truncateWithEllipsis(int cutoff, String myString) {
  return (myString.length <= cutoff)
    ? myString
    : '${myString.substring(0, cutoff)}...';
}