Dart lists: A multiline map method example

Many times when you use the Dart map method on a list, you’ll write the method as a one-line function. For example, the second line of code here shows a one-line map method on a Dart list:

final xs = ['aaa', 'bb', 'cccc'];
final ys = xs.map((String s) => s.length);  //one-line 'map'
ys.forEach(print);

However, there are also times when you need to write a multiline Dart map method. For that case, this example demonstrates the multiline map method syntax:

void main() {

    final xs = ['aaa', 'bb', 'cccc'];

    // a multiline map method on a list
    final ys = xs.map((String s) {
        final len = s.length;
        // any other code you need here
        return len;
    });
    
    // prints "3 2 4" (on multiple lines)
    ys.forEach(print);

}

As shown in that Dart code, you expand the Dart one-line-function syntax into a multiline syntax, which is very similar to writing a multiline Dart function.

In both of those examples, the String s portion of the code can also be written as just s (though I have seen the Dart compiler do weird things when you leave the type of of the second example).

Using a multiline function with map

Similarly, if you want to use a multiline function with map on a list, here’s an example that shows how this works:

// [1] your custom function
int _stringToLength(String s) {
  // as many lines of code here as necessary
  return s.length;
}

void main() {

    final xs = ['aaa', 'bb', 'cccc'];

    // [2] call the function with 'map' here
    final ys = xs.map((String s) => _stringToLength(s));
    
    // prints "3 2 4" (on multiple lines)
    ys.forEach(print);

}

As shown in this example, here you can use the single line map method syntax to call your multiline function.

Depending on your needs, one of these two approaches should solve the problem.

Summary

In summary, if you need to write a multiline map method to work with a Dart list, I hope these examples are helpful.