splitInLines method

List<String> splitInLines(
  1. int lineLength, {
  2. String? separator,
  3. int? firstLineDecrease,
})

Divides a String in lines of the length required. The default separator is blank, but it can be set a different char It is possible to set a different length for the first line.

Example: 'consequatur mollit est'.splitInLines(11) returns 'consequatur', ' mollit est'

Implementation

List<String> splitInLines(int lineLength,
    {String? separator, int? firstLineDecrease}) {
  separator ??= ' ';
  firstLineDecrease ??= 0;
  final buffer = StringBuffer();
  final ret = <String>[];
  var requiredLength = lineLength - firstLineDecrease;

  void writeAndFlushBuffer({String? addString}) {
    if (addString != null) {
      buffer.write(addString);
    }
    if (buffer.isNotEmpty) {
      ret.add('$buffer');
      buffer.clear();
      requiredLength = lineLength;
    }
  }

  if (requiredLength < 1) {
    writeAndFlushBuffer(addString: ' ');
  }

  final parts = split(separator);
  for (var part in parts) {
    if (buffer.length +
            part.length +
            (part == parts.last ? 0 : separator.length) >
        requiredLength) {
      writeAndFlushBuffer();
    }

    var idx = 0;
    if (part == parts.last) {
      for (; idx + requiredLength < part.length; idx += requiredLength) {
        writeAndFlushBuffer(
            addString: part.substring(idx, idx + requiredLength));
      }
      if (idx < part.length) {
        buffer.write(part.substring(idx));
      }
    } else {
      for (;
          idx + requiredLength < part.length + separator.length;
          idx += requiredLength) {
        writeAndFlushBuffer(
            addString: part.substring(idx, idx + requiredLength));
      }
      if (idx < part.length) {
        buffer.write(part.substring(idx));
      }
      buffer.write(separator);
    }
  }
  return ret..add('$buffer');
}