indent method

String indent(
  1. String prefix, {
  2. String? firstPrefix,
  3. bool trimWhitespace = true,
  4. bool indentEmpty = false,
})

Adds a prefix to the beginning of each line.

  • If defined, firstPrefix replaces prefix on the first line.
  • trimWhitespace trims the each line from existing whitespace.
  • indentEmpty indents empty lines as well.

Implementation

String indent(
  String prefix, {
  String? firstPrefix,
  bool trimWhitespace = true,
  bool indentEmpty = false,
}) {
  final result = <String>[];
  for (var line in split('\n')) {
    if (trimWhitespace) {
      line = line.trim();
    }
    if (line.isEmpty && !indentEmpty) {
      result.add(line);
    } else {
      if (result.isEmpty && firstPrefix != null) {
        result.add('$firstPrefix$line');
      } else {
        result.add('$prefix$line');
      }
    }
  }
  return result.join('\n');
}