wrapText method

String wrapText(
  1. String text,
  2. int maxWidth
)

Wraps text to fit within a given width.

Args: text (String): The text to wrap. maxWidth (int): The maximum width for the text bounding box.

Returns: String: The wrapped text.

Implementation

String wrapText(String text, int maxWidth) {
  final lines = text.split("\n");
  var output = "";
  for (final line in lines) {
    if (getTextWidth(line) <= maxWidth) {
      output += "$line\n";
    } else {
      var thisLine = "";
      final words = line.split(" ");
      for (final word in words) {
        if (getTextWidth("$thisLine $word") > maxWidth) {
          output += "$thisLine\n";
          thisLine = word;
        } else if (thisLine.isEmpty) {
          thisLine = word;
        } else {
          thisLine += " $word";
        }
      }
      if (thisLine.isNotEmpty) {
        output += "$thisLine\n";
      }
    }
  }
  return output.trimRight();
}