dedent method
Removes the common leading whitespace from every line.
The amount removed is the minimum of leading whitespace lengths (excluding fully blank lines).
Line breaks are normalized to \n. Returns a new string with common indent removed.
Example:
' a\n b'.dedent(); // 'a\nb'
' a\n b'.dedent(); // 'a\n b'
Implementation
@useResult
String dedent() {
if (isEmpty) return this;
final List<String> lines = split('\n');
int? minLead;
for (final String line in lines) {
if (!line.trim().isEmpty) {
final int lead = line.length - line.trimLeft().length;
if (minLead == null || lead < minLead) minLead = lead;
}
}
if (minLead == null || minLead == 0) {
return this;
}
final lead = minLead;
return lines
.map((String line) => line.length >= lead ? line.replaceRange(0, lead, '') : line)
.join('\n');
}