Dart Arrow Functions
Dart Arrow Functions
Many functions contain only one line of code that returns a value.
For these functions, Dart has a shorter way to write them, called the arrow syntax.
You use the arrow => instead of curly brackets and the return keyword.
This is a normal function that squares a number:
Result:
25
Here is the same function, written with the arrow syntax:
Result:
25
The code => x * x; means the same as { return x * x; }.
Syntax
An arrow function has a return type, a name, parameters, the arrow, and one expression:
returnType functionName(parameters) => expression;
An expression is a piece of code that gives a value, like a + b or 'Hello $name'.
The value of the expression is returned automatically.
Do not write the return keyword after the arrow.
If you do, the program does not run:
Result:
main.dart:1:26: Error: Unexpected token 'return'.
int add(int a, int b) => return a + b;
^^^^^^
More Examples
Arrow functions can take more than one parameter:
Example
int add(int a, int b) => a + b;
void main() {
print(add(3, 4));
print(add(10, 20));
}
Try it Yourself »
Result:
7
30
They can return a string:
Example
String greet(String name) => 'Hello, $name!';
void main() {
print(greet('Liam'));
print(greet('Emma'));
}
Try it Yourself »
Result:
Hello, Liam!
Hello, Emma!
They can also return a bool, which is useful for checks:
Example
bool isAdult(int age) => age >= 18;
void main() {
print(isAdult(20));
print(isAdult(15));
}
Try it Yourself »
Result:
true
false
You can use the conditional operator ? : to choose between two values in one expression:
Example
String grade(int score) => score >= 50 ? 'Pass' : 'Fail';
void main() {
print(grade(75));
print(grade(30));
}
Try it Yourself »
Result:
Pass
Fail
Void Arrow Functions
An arrow function can also have the return type void.
This is common when the function only calls print():
Example
void sayHello(String name) => print('Hello, $name');
void main() {
sayHello('Olivia');
sayHello('Noah');
}
Try it Yourself »
Result:
Hello, Olivia
Hello, Noah
Only One Expression
The arrow syntax only works with one expression.
You cannot put statements like if, for or a variable declaration after the arrow.
When a function needs more than one statement, use a normal function with curly brackets:
Example
String check(int x) {
if (x > 0) {
return 'positive';
}
return 'zero or negative';
}
void main() {
print(check(5));
print(check(-2));
}
Try it Yourself »
Result:
positive
zero or negative
Tip: Use the arrow syntax for short functions that fit on one line.
It makes your code shorter and easier to read.