wordWrap method

String wordWrap({
  1. int width = 75,
  2. String lineBreak = '\n',
  3. bool cutWord = false,
})

Return a String wrapped at the specified length.

Name Description Default Value
width The number of characters at which the string will be wrapped 75
lineBreak The characters which will use as break "\n"
cutWord Specifies whether a word exceeded width should be break false

Example:

print('Hello World'.wordWrap(width: 3)); // => 'Hello\nWorld'
print('Hello World'.wordWrap(width: 3, lineBreak: '\t')); // => 'Hello\tWorld'
print('Hello World'.wordWrap(width: 3, cutWord: true)); // => 'Hel\nlo\nWor\nld'

Implementation

String wordWrap(
    {int width = 75, String lineBreak = '\n', bool cutWord = false}) {
  final List<String> words = trim().split(RegExp(r' |\n|\t'));
  final List<String> lines = [];

  if (cutWord) {
    final List<String> longWords =
        words.skipWhile((value) => value.length < width).toList();

    for (var word in longWords) {
      final List<String> reducedWord = [];
      final String temp = word;

      while (word.isNotEmpty) {
        final int range = word.length > width ? width : word.length;

        reducedWord.add(word.substring(0, range).trim());
        word = word.replaceRange(0, range, '');
      }

      words.insertAll(words.indexOf(temp), reducedWord);
      words.remove(temp);
    }
  }

  while (words.isNotEmpty) {
    for (int i = 0; i < words.length; i++) {
      final String line = words
          .getRange(0, words.length - i)
          .reduce((value, element) => '$value $element');

      if (line.length <= width ||
          (words.length - i == 1 && line.length > width)) {
        lines.add(line);
        words.removeRange(0, words.length - i);
        break;
      }
    }
  }

  return lines.join(lineBreak);
}