AI Reading
Quick summary of this article
Dart functions are reusable blocks of code that can take parameters, perform tasks, and return values. They are essential for organizing code and avoiding repetition. Functions can have return types, names, parameters, and bodies, and they support various features like optional parameters, anonymous functions, and closures.
- Functions can return values using the
returnstatement; if no return type is specified, they implicitly returnnull. - Optional parameters can be named (using curly braces
{}) or positional (using square brackets[]), and both support default values. - Anonymous functions (lambdas) can be assigned to variables or passed as arguments; arrow functions (
=>) offer a concise syntax for simple expressions. - Higher-order functions can accept other functions as arguments or return them, enabling functional programming patterns.
- Closures capture variables from their lexical scope, allowing functions to retain access to data even when called outside their original context.
Dart Functions
In Dart, functions are fundamental building blocks that allow you to encapsulate reusable blocks of code. They can take input parameters, perform tasks, and optionally return a value. Here’s an overview of Dart functions with examples:
Example of a Basic Function
// A function to greet a person
void greet() {
print('Hello, Alice');
}
void main() {
// Calling the greet function
greet(); // Output: Hello, Alice!
greet('Bob'); // Output: Hello, Bob!
}
Function Components
1. Return Type: Specifies the type of value that the function will return. Use void if the function does not return any value.
2. Function Name: A descriptive name that identifies the function.
3.Parameters: Input values passed to the function. They are optional, and multiple parameters can be separated by commas.
4.Function Body: Contains the code that defines what the function does.
5.Return Statement: Optional statement used to return a value from the function. Functions without a return type implicitly return null.
Functions with Return Values
// A function to calculate the sum of two numbers
int sum(int a, int b) {
return a + b;
}
void main() {
// Calling the sum function and storing the result in a variable
int result = sum(5, 3);
print('Sum: $result'); // Output: Sum: 8
}
Optional Parameters
Named Optional Parameters with Default Values
Your example demonstrates this:
void printDetails(String name, {int age = 30, String city = 'Unknown'}) {
print('Name: $name, Age: $age, City: $city');
}
void main() {
printDetails('Alice'); // Output: Name: Alice, Age: 30, City: Unknown
printDetails('Bob', age: 25); // Output: Name: Bob, Age: 25, City: Unknown
printDetails('Charlie', age: 40, city: 'New York'); // Output: Name: Charlie, Age: 40, City: New York
}
In this case, age and city are named optional parameters with default values.
Positional Optional Parameters
You can define positional optional parameters by enclosing them in square brackets []. These parameters can be left out when calling the function:
void printDetails(String name, [int? age, String? city]) {
print('Name: $name, Age: ${age ?? 'Not specified'}, City: ${city ?? 'Unknown'}');
}
void main() {
printDetails('Alice'); // Output: Name: Alice, Age: Not specified, City: Unknown
printDetails('Bob', 25); // Output: Name: Bob, Age: 25, City: Unknown
printDetails('Charlie', 40, 'New York'); // Output: Name: Charlie, Age: 40, City: New York
}
In this example, age and city are positional optional parameters. If not provided, they default to null, so we use the null-aware operator (??) to handle their default values.
Named Parameters
Named parameters are specified using curly braces {}. They allow you to specify parameters in any order and provide clarity in function calls:
// A function with named parameters
void printOrderDetails({String customer, String product, int quantity}) {
print('Customer: $customer, Product: $product, Quantity: $quantity');
}
void main() {
printOrderDetails(customer: 'Alice', product: 'Laptop', quantity: 1);
// Output: Customer: Alice, Product: Laptop, Quantity: 1
printOrderDetails(product: 'Mouse', quantity: 2, customer: 'Bob');
// Output: Customer: Bob, Product: Mouse, Quantity: 2
}
Anonymous Functions (Lambda Expressions)
Anonymous functions, also known as lambda expressions or closures, are functions without a name. They can be assigned to variables or passed as arguments to other functions:
void main() {
// Example of an anonymous function
var multiply = (int a, int b) {
return a * b;
};
// Using the anonymous function
print('Result: ${multiply(5, 3)}'); // Output: Result: 15
}
Arrow Functions
int add(int a, int b) => a + b;
void main() {
print(add(3, 4)); // Output: 7
}
Higher-Order Functions
Dart supports higher-order functions, which are functions that take other functions as parameters or return a function. This enables powerful functional programming patterns:
// A higher-order function that takes a function as an argument
void executeFunction(void Function() function) {
print('Executing function...');
function();
}
void main() {
// Passing a named function as an argument
void sayHello() {
print('Hello!');
}
executeFunction(sayHello); // Output: Executing function... \n Hello!
}
Function Closures
A closure is a function object that has access to variables in its lexical scope, even when the function is used outside of its original scope:
Function makeAdder(int addBy) {
return (int i) => addBy + i;
}
void main() {
var add2 = makeAdder(2);
print(add2(3)); // Output: 5
var add4 = makeAdder(4);
print(add4(3)); // Output: 7
}
