defaultTextWrapper function

List<String> defaultTextWrapper(
  1. String text,
  2. int width
)

A default TextWrapper that wraps on word boundaries (determined by the presence of spaces), using character wrapping as a fallback.

Implementation

List<String> defaultTextWrapper(String text, int width) {
  var lines = <String>[];

  for (var line in text.split('\n')) {
    if (line.length < width) {
      lines.add(line);
      continue;
    }

    var buffer = StringBuffer();
    for (var word in line.split(RegExp(r'\s+')).where((w) => w.isNotEmpty)) {
      var needsSpaceBeforeWord = buffer.isNotEmpty;
      var spaceNeeded = word.length + (needsSpaceBeforeWord ? 1 : 0);

      if (width - buffer.length < spaceNeeded) {
        lines.add(buffer.toString());
        buffer.clear();
        needsSpaceBeforeWord = false;

        if (word.length > width) {
          // Remove full line widths from the word.
          int i;
          for (i = 0;
              i < _nearestMultiple(word.length, of: width);
              i += width) {
            lines.add(word.substring(i, i + width));
          }

          // Save the rest to add to the start of a new line.
          word = word.substring(i);
        }
      }

      if (needsSpaceBeforeWord) {
        buffer.write(' ');
      }

      buffer.write(word);
    }

    if (buffer.isNotEmpty) {
      lines.add(buffer.toString());
    }
  }

  return lines;
}