splitObjectIfTooLong method

List<String> splitObjectIfTooLong({
  1. required String object,
  2. String subMessage = '',
})

Splits a given object into multiple lines of maximum parameters.maxLength characters, optionally adding a subMessage at the beginning of each line.

Returns a list of strings, each representing a line of the split message.

Implementation

List<String> splitObjectIfTooLong(
    {required String object, String subMessage = ''}) {
  List<String> lines = [];
  // Create variable of object and subMessage
  String fullLine = "$subMessage$object";
  // Check if total length is too big and split the message in multi-line
  while (fullLine.length > parameters.maxLength - 2) {
    int lastSpace = fullLine.lastIndexOf(' ', parameters.maxLength - 2);
    // If the String message is just a big charactere length
    if (lastSpace == -1) {
      lastSpace = parameters.maxLength - 2;
    }
    lines.add(fullLine.substring(0, lastSpace));
    // Remove the first space on other lines when split
    if (fullLine.startsWith(" ")) {
      fullLine = fullLine.substring(lastSpace + 1);
    } else {
      fullLine = fullLine.substring(lastSpace);
    }
  }
  // Remove the first space on other lines when split
  if (fullLine.startsWith(" ")) {
    lines.add(fullLine.substring(1));
  } else {
    lines.add(fullLine);
  }
  // Remove subMessage
  lines[0] = lines[0].substring(subMessage.length);
  return lines;
}