Dart

11. Dart Functions

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
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *