All lessons

Power Tools: Arrow Syntax & List Methods

9 min · Dart

Skip the curly braces with arrow functions, and transform lists with map and where.

Dart · Power Tools: Arrow Syntax & List Methods0/5 cleared

Enemy 1 of 5

Arrow syntax for one-line functions

This function squares a number using arrow syntax, which skips the braces and return when the body is one expression. main prints the square of 6. Press Run to see it.

Why this works

When a function's entire body is just a single expression whose value you want to return, Dart lets you skip the curly braces and return keyword entirely with arrow syntax: => expression is shorthand for { return expression; }. int square(int n) => n * n; behaves identically to writing out the full block form, just more compactly.

Arrow syntax works anywhere a function body would normally go (top-level functions, methods on a class, and the anonymous functions you pass into .map() and .where() below), but it's only valid for a single expression. The moment your logic needs more than one statement (like an if or a loop), you need to switch back to the full { } block form.

You
Binary Treant
Loading editor…
Sign up to fightThis one runs on our servers, so it needs a free account.