Dart: How to remove leading spaces in a multiline string (using splitMapJoin)

As far as I know, there’s no built-in way to remove spaces from a multiline string in Dart, but you can write your own Dart function to do this.

For example, I just dug into the splitMapJoin method of the Dart String class, and wrote a stripMargin function like this:

String stripMargin(String s) {
    return s.splitMapJoin(
        RegExp(r'^', multiLine: true),
        onMatch: (_) => '\n',
        onNonMatch: (n) => n.trim(),

Now, given a multiline string like this:

final s = '''
    four score
    and seven
    years ago

When you print it like this:


you’ll get this left-trimmed multiline output:

four score
and seven
years ago

I haven’t tested that beyond this example, but if you need a way to left-trim a Dart multiline string — i.e., to remove the leading spaces from a multiline string — I hope this function is helpful.

P.S. — The name stripMargin comes from a method of the same name on Scala multiline strings.