wordWrap method

String wordWrap(
  1. int maxWidth
)

Wraps this string at maxWidth characters, breaking at word boundaries.

'Hello World Foo'.wordWrap(7) // 'Hello\nWorld\nFoo'

Implementation

String wordWrap(int maxWidth) {
  assert(maxWidth > 0, 'maxWidth must be > 0');
  final words = split(' ');
  final lines = <String>[];
  final current = StringBuffer();
  for (final word in words) {
    if (current.isEmpty) {
      current.write(word);
    } else if (current.length + 1 + word.length <= maxWidth) {
      current.write(' $word');
    } else {
      lines.add(current.toString());
      current.clear();
      current.write(word);
    }
  }
  if (current.isNotEmpty) lines.add(current.toString());
  return lines.join('\n');
}