What are Arrow Functions?
An arrow function (also called a lambda or fat-arrow function) is a concise syntax for writing single-expression functions. Instead of { return expression; }, you write => expression.
Syntax
// Full function
int add(int a, int b) {
return a + b;
}
// Arrow function (equivalent)
int add(int a, int b) => a + b;
Examples
// Math functions
int square(int n) => n * n;
double circleArea(double r) => 3.14159 * r * r;
bool isAdult(int age) => age >= 18;
String greet(String name) => 'Hello, $name!';
void main() {
print(square(5)); // 25
print(circleArea(3).toStringAsFixed(2)); // 28.27
print(isAdult(20)); // true
print(greet('Dart')); // Hello, Dart!
// Arrow function as variable
var double_ = (int n) => n * 2;
print(double_(7)); // 14
}
Output:25
28.27
true
Hello, Dart!
14
Arrow Functions as Arguments
Arrow functions are commonly passed as callbacks to higher-order functions:
List<int> numbers = [1, 2, 3, 4, 5, 6, 7, 8];
// Filter even numbers
var evens = numbers.where((n) => n % 2 == 0).toList();
print(evens); // [2, 4, 6, 8]
// Map to squares
var squares = numbers.map((n) => n * n).toList();
print(squares); // [1, 4, 9, 16, 25, 36, 49, 64]
// Reduce to sum
var sum = numbers.reduce((a, b) => a + b);
print(sum); // 36
⚠️ Common Mistakes
- Using arrow syntax for multi-statement functions —
=> only works for a single expression.
- Forgetting that arrow functions implicitly return the expression value.
🧠 Quiz
1. What does int triple(int n) => n * 3; return for n=4?
2. Can an arrow function contain multiple statements?
- A) Yes
- B) No ✅
- C) Only with semicolons
- D) Only inside classes
Summary
Arrow functions use => expression as a shorthand for single-expression functions. They implicitly return the expression value. They are widely used as callbacks in where(), map(), reduce(), and other higher-order functions.