truncateAtGrapheme method

  1. @useResult
String truncateAtGrapheme(
  1. int maxGraphemes
)

Truncates at grapheme boundary so no emoji or extended grapheme is cut.

Returns at most maxGraphemes graphemes. maxGraphemes must be non-negative.

Throws ArgumentError if maxGraphemes is negative.

Example:

'hellođź‘‹world'.truncateAtGrapheme(5);  // 'hello'
'ab'.truncateAtGrapheme(10);           // 'ab'

Implementation

@useResult
String truncateAtGrapheme(int maxGraphemes) {
  if (maxGraphemes < 0) {
    throw ArgumentError(_kErrMaxGraphemesNonNegative, _kParamMaxGraphemes);
  }
  if (isEmpty) return this;
  final Characters chars = characters;
  if (maxGraphemes >= chars.length) return this;
  return chars.take(maxGraphemes).string;
}