๐ŸŽ“ A1Learner
๐Ÿ”
0 of 40 lessons completed

Dart Arrow Functions

An arrow function is a short function that holds one expression. The arrow returns the value of that expression.

A block body with one return

This function holds one statement inside curly braces. The statement returns three times the input.

int triple(int n) {
  return n * 3;
}

void main() {
  print(triple(4));
}

The same function with an arrow

The arrow form holds the same calculation in one line. The printed value matches the block form.

int triple(int n) => n * 3;

void main() {
  print(triple(4));
}

An arrow function that builds text

This arrow function returns a greeting with a name inside it. The greeting is the whole output.

String greet(String name) => 'Hello, $name';

void main() {
  print(greet('Ana'));
}

An arrow function that prints

A void arrow function can hold one print call as its expression. The call shows double the input.

void show(int n) => print(n * 2);

void main() {
  show(7);
}

Example

int square(int n) => n * n;

String describe(int n) => '$n squared is ${square(n)}';

void main() {
  print(square(3));
  print(describe(3));
}

Key points

  • Use => to write a function that holds one expression.
  • The value after the arrow is the return value.
  • A block body uses curly braces and the word return.
  • An arrow function keeps its name, its parameters, and its return type.
  • Use a block body when a function needs more than one statement.

In this example, square is an arrow function that multiplies a number by itself. The first print shows 9 for the input 3. describe is an arrow function that builds text with a call to square inside it. The second print shows that text.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท DartPad

Exercise

Which symbol writes an arrow function?