Conciseness: Arrow functions make the code shorter and cleaner.
Readability: Ideal for single-line expressions.
Inline Use: Useful in lambda expressions (e.g., map, forEach, etc.).
Arrow functions can only contain a single expression. For more complex logic, use standard {} functions.
In Dart, arrow functions are a concise way to write functions with a single expression. These functions are defined using the => syntax, also known as the fat arrow. Arrow functions are primarily used to make the code shorter and more readable, especially for simple operations.
returnType functionName(parameters) => expression;
=> replaces the curly braces {} and the return keyword for a single expression.
Arrow functions must only have a single expression (not a block of code).
1. Basic Example
int add(int a, int b) => a + b;
void main() {
print(add(5, 3)); // Output: 8
}
2. Using Arrow Function in Void Methods
void greet(String name) => print('Hello, $name!');
void main() {
greet('Alice'); // Output: Hello, Alice!
}
3. Arrow Functions with Default Parameters
String greet(String name, [String suffix = '']) => 'Hello, $name$suffix!';
void main() {
print(greet('Alice')); // Output: Hello, Alice!
print(greet('Alice', ', how are you?')); // Output: Hello, Alice, how are you?
}
4. Arrow Functions with List Operations
void main() {
List<int> numbers = [1, 2, 3, 4];
List<int> squared = numbers.map((n) => n * n).toList();
print(squared); // Output: [1, 4, 9, 16]
}
5. Arrow Function Inside Higher-Order Functions
void main() {
List<String> names = ['Alice', 'Bob', 'Charlie'];
names.forEach((name) => print('Hi, $name!'));
// Output:
// Hi, Alice!
// Hi, Bob!
// Hi, Charlie!
}
6. Getter with Arrow Function
class Circle {
final double radius;
Circle(this.radius);
// Arrow function as a getter
double get area => 3.14 * radius * radius;
}
void main() {
Circle c = Circle(5);
print(c.area); // Output: 78.5
}
7. Arrow Function with Conditional Expression
String checkNumber(int n) => n > 0 ? 'Positive' : 'Negative or Zero';
void main() {
print(checkNumber(5)); // Output: Positive
print(checkNumber(-2)); // Output: Negative or Zero
}
String checkEvenOdd(int number) => number % 2 == 0 ? 'Even' : 'Odd';
void main() {
print(checkEvenOdd(5)); // Output: Odd
}
double areaOfCircle(double radius) => 3.14 * radius * radius;
void main() {
print(areaOfCircle(5)); // Output: 78.5
}
String greet(String name) => 'Hello, $name!';
void main() {
print(greet('Alice')); // Output: Hello, Alice!
}
int multiply(int a, int b) => a * b;
void main() {
print(multiply(4, 6)); // Output: 24
}
double celsiusToFahrenheit(double celsius) => (celsius * 9 / 5) + 32;
void main() {
print(celsiusToFahrenheit(25)); // Output: 77.0
}
void main() {
List<int> numbers = [1, 2, 3, 4, 5, 6];
List<int> oddNumbers = numbers.where((n) => n % 2 != 0).toList();
print(oddNumbers); // Output: [1, 3, 5]
}
void main() {
List<int> numbers = [1, 2, 3, 4];
List<int> squares = numbers.map((n) => n * n).toList();
print(squares); // Output: [1, 4, 9, 16]
}
void main() {
List<String> names = ['Alice', 'Bob', 'Charlie'];
names.forEach((name) => print('Hi, $name!'));
// Output:
// Hi, Alice!
// Hi, Bob!
// Hi, Charlie!
}
int factorial(int n) => n <= 1 ? 1 : n * factorial(n - 1);
void main() {
print(factorial(5)); // Output: 120
}
bool isPrime(int n) => n > 1 && List.generate(n - 2, (i) => i + 2).every((i) => n % i != 0);
void main() {
print(isPrime(7)); // Output: true
print(isPrime(4)); // Output: false
}
int max(int a, int b) => a > b ? a : b;
void main() {
print(max(5, 10)); // Output: 10
}
int sum(List<int> numbers) => numbers.reduce((a, b) => a + b);
void main() {
print(sum([1, 2, 3, 4, 5])); // Output: 15
}
double perimeterOfRectangle(double length, double width) => 2 * (length + width);
void main() {
print(perimeterOfRectangle(5, 3)); // Output: 16
}
String reverse(String input) => input.split('').reversed.join();
void main() {
print(reverse('Dart')); // Output: traD
}
void main() {
List<int> numbers = [-3, -1, 0, 2, 4];
List<int> positiveNumbers = numbers.where((n) => n > 0).toList();
print(positiveNumbers); // Output: [2, 4]
}
String greet(String name, [String suffix = '']) => 'Hello, $name$suffix!';
void main() {
print(greet('Alice')); // Output: Hello, Alice!
print(greet('Alice', ', how are you?')); // Output: Hello, Alice, how are you?
}
bool isPalindrome(String input) => input == input.split('').reversed.join();
void main() {
print(isPalindrome('madam')); // Output: true
print(isPalindrome('dart')); // Output: false
}
void main() {
List<String> words = ['hello', 'dart', 'flutter'];
List<String> upperCaseWords = words.map((word) => word.toUpperCase()).toList();
print(upperCaseWords); // Output: [HELLO, DART, FLUTTER]
}
int calculateAge(int birthYear) => DateTime.now().year - birthYear;
void main() {
print(calculateAge(1990)); // Output: Current year - 1990
}
An arrow function provides a shorter syntax for functions that contain a single expression.
void main() {
// Arrow function to calculate the cube of a number
int cube(int num) => num * num * num;
// Calling the function and printing the result
print("The cube of 3 is: ${cube(3)}");
}
-----------------------------------------------------------------------------------------------------------------------------------
Arrow functions are defined using the syntax => expression.
void main() {
int square(int x) => x * x;
print(square(5)); // Output: 25
}
void main() {
bool isEven(int x) => x % 2 == 0;
print(isEven(4)); // Output: true
print(isEven(5)); // Output: false
}
void main() {
String concatenate(String str1, String str2) => '$str1 $str2';
print(concatenate("Hello", "World")); // Output: Hello World
}
void main() {
double areaOfCircle(double radius) => 3.14159 * radius * radius;
print(areaOfCircle(5)); // Output: 78.53975
}
void main() {
double celsiusToFahrenheit(double celsius) => (celsius * 9 / 5) + 32;
print(celsiusToFahrenheit(25)); // Output: 77.0
}
void main() {
int max(int a, int b) => (a > b) ? a : b;
print(max(10, 20)); // Output: 20
}
void main() {
double simpleInterest(double principal, double rate, double time) => (principal * rate * time) / 100;
print(simpleInterest(1000, 5, 2)); // Output: 100.0
}
void main() {
int getLength(String str) => str.length;
print(getLength("Dart")); // Output: 4
}
void main() {
bool isPositive(int x) => x > 0;
print(isPositive(10)); // Output: true
print(isPositive(-5)); // Output: false
}
void main() {
int multiply(int a, int b) => a * b;
print(multiply(4, 5)); // Output: 20
}
You can create functions without a name, known as anonymous functions or lambda expressions.
Ex=
void main() {
// List of numbers
List<int> numbers = [1, 2, 3, 4, 5];
// Anonymous function passed to forEach
numbers.forEach((num) {
print("Number: $num");
});
}
----------------------------------------------------------------------------------------------------------------------------
An anonymous function is a function without a name, often used for short-term tasks where defining a separate function is unnecessary. Anonymous functions are commonly used as arguments for higher-order functions or event handlers.
void main() {
List<String> names = ["Alice", "Bob", "Charlie"];
names.forEach((name) {
print("Hello, $name!");
});
// Output:
// Hello, Alice!
// Hello, Bob!
// Hello, Charlie!
}
void main() {
List<int> numbers = [1, 2, 3, 4];
List<int> doubled = numbers.map((n) => n * 2).toList();
print(doubled); // Output: [2, 4, 6, 8]
}
void main() {
List<int> numbers = [10, 5, 2, 8];
numbers.sort((a, b) => a.compareTo(b));
print(numbers); // Output: [2, 5, 8, 10]
}
void main() {
List<int> numbers = [1, 2, 3, 4, 5, 6];
List<int> evens = numbers.where((n) => n % 2 == 0).toList();
print(evens); // Output: [2, 4, 6]
}
void main() {
List<int> numbers = [1, 2, 3, 4];
int sum = numbers.reduce((a, b) => a + b);
print("Sum: $sum"); // Output: Sum: 10
}
void main() {
void repeat(int times, Function task) {
for (int i = 0; i < times; i++) {
task();
}
}
repeat(3, () => print("Dart is great!"));
// Output:
// Dart is great!
// Dart is great!
// Dart is great!
}
void main() {
List<int> numbers = [1, 2, 3, 4, 5, 6];
List<int> odds = numbers.where((n) => n % 2 != 0).toList();
print(odds); // Output: [1, 3, 5]
}
void main() {
List<int> numbers = [1, 2, 3, 4, 5];
List<String> result = numbers.map((n) => n % 2 == 0 ? "Even" : "Odd").toList();
print(result); // Output: [Odd, Even, Odd, Even, Odd]
}
void main() {
void executeOperation(int a, int b, Function operation) {
print("Result: ${operation(a, b)}");
}
executeOperation(5, 3, (a, b) => a + b); // Output: Result: 8
executeOperation(5, 3, (a, b) => a * b); // Output: Result: 15
}
void main() {
List<int> numbers = [10, 15, 20, 25];
// Anonymous function to print only numbers greater than 15
numbers.forEach((n) {
if (n > 15) print("Filtered number: $n");
});
// Output:
// Filtered number: 20
// Filtered number: 25
}