Summary: in this tutorial, you’ll learn about Dart arrow functions to make functions more concise.
Introduction to the Dart Arrow Functions
If a function body has only one line, you can use an arrow function with the following syntax to make it more compact:
returnType functionnName(parameters) => expression;
Code language: Dart (dart)
In this syntax, the return type of the function must match the type of the value returned by the expression.
For example, the following defines the add()
function that returns the sum of two integers:
int add(int x, int y) {
return x + y;
}
Code language: Dart (dart)
Since the body of the add()
function has only one line, you can convert it to an arrow function like this:
int add(int x, int y) => x + y;
Code language: Dart (dart)
Also, if an anonymous function has one line, you can convert it to an arrow function to make it more compact:
(parameters) => expression;
Code language: Dart (dart)
For example, the following defines an anonymous function that returns the sum of two integers and assigns it to the add variable:
void main() {
var add = (int x, int y) {
return x + y;
};
print(add(10, 20));
}
Code language: Dart (dart)
Since the anonymous function has one line, you can use the arrow function syntax like this:
void main() {
var add = (int x, int y) => x + y;
print(add(10, 20));
}
Code language: Dart (dart)
Summary
- Use arrow functions for the functions with one line to make the code more concise.