wrapAtChars method

  1. @useResult
String wrapAtChars(
  1. int width
)

Wraps this string at width character boundaries (grapheme-safe). Returns chunks joined by newline. Audited: 2026-06-12 11:26 EDT

Implementation

@useResult
String wrapAtChars(int width) {
  // A width below one has no sensible chunk size, and a string already within
  // the width needs no wrapping — return it unchanged in both cases.
  if (width < 1) return this;
  // Measure and slice in grapheme clusters (Characters), not code units, so an
  // emoji or combining mark is never split across a line boundary.
  final Characters charSeq = characters;
  if (charSeq.length <= width) return this;
  // Pre-size the parts list to the exact ceil(length/width) so it is filled by
  // index without intermediate growth.
  final int partCount = (charSeq.length / width).ceil();
  final List<String> parts = List<String>.filled(partCount, '');
  for (int i = 0; i < partCount; i++) {
    // Clamp the final chunk's end to the sequence length so the last (short)
    // line does not read past the end.
    final int start = i * width;
    final int end = (start + width) > charSeq.length ? charSeq.length : start + width;
    parts[i] = charSeq.getRange(start, end).string;
  }
  return parts.join('\n');
}