String wrapText()

in lib/src/utils.dart [35:71]


String wrapText(String text, {int? length, int? hangingIndent}) {
  if (length == null) return text;
  hangingIndent ??= 0;
  var splitText = text.split('\n');
  var result = <String>[];
  for (var line in splitText) {
    var trimmedText = line.trimLeft();
    final leadingWhitespace =
        line.substring(0, line.length - trimmedText.length);
    List<String> notIndented;
    if (hangingIndent != 0) {
      // When we have a hanging indent, we want to wrap the first line at one
      // width, and the rest at another (offset by hangingIndent), so we wrap
      // them twice and recombine.
      var firstLineWrap = wrapTextAsLines(trimmedText,
          length: length - leadingWhitespace.length);
      notIndented = [firstLineWrap.removeAt(0)];
      trimmedText = trimmedText.substring(notIndented[0].length).trimLeft();
      if (firstLineWrap.isNotEmpty) {
        notIndented.addAll(wrapTextAsLines(trimmedText,
            length: length - leadingWhitespace.length - hangingIndent));
      }
    } else {
      notIndented = wrapTextAsLines(trimmedText,
          length: length - leadingWhitespace.length);
    }
    String? hangingIndentString;
    result.addAll(notIndented.map<String>((String line) {
      // Don't return any lines with just whitespace on them.
      if (line.isEmpty) return '';
      var result = '${hangingIndentString ?? ''}$leadingWhitespace$line';
      hangingIndentString ??= ' ' * hangingIndent!;
      return result;
    }));
  }
  return result.join('\n');
}