wrap method

List<String> wrap(
  1. int width
)

Wraps the string to the specified width.

Example:

'long text here'.wrap(5); // ['long ', 'text ', 'here']

Implementation

List<String> wrap(int width) {
  assert(width > 0, 'width must be positive');
  if (isEmpty) return [];
  final words = split(' ');
  final lines = <String>[];
  var currentLine = '';

  for (final word in words) {
    if ((currentLine + word).length <= width) {
      currentLine = currentLine.isEmpty ? word : '$currentLine $word';
    } else {
      if (currentLine.isNotEmpty) lines.add(currentLine);
      currentLine = word;
    }
  }
  if (currentLine.isNotEmpty) lines.add(currentLine);
  return lines;
}