dedent function

String dedent(
  1. String text
)

Remove the common leading whitespace from all non-empty lines.

Implementation

String dedent(String text) {
  final lines = text.split('\n');
  final nonEmpty = lines.where((l) => l.trimLeft().isNotEmpty);
  if (nonEmpty.isEmpty) return text;

  final minIndent = nonEmpty
      .map((l) {
        final stripped = l.trimLeft();
        return l.length - stripped.length;
      })
      .reduce(math.min);

  return lines
      .map((l) {
        if (l.trimLeft().isEmpty) return l.trimRight();
        return l.substring(math.min(minIndent, l.length));
      })
      .join('\n');
}