Dart Functions


In Dart, functions are fundamental building blocks that allow you to encapsulate code for reusability and organization. Here’s an overview of how functions work in Dart:

1. Defining Functions

You can define a function using the following syntax:

returnType functionName(parameters) { // function body }

Example:

int add(int a, int b) { return a + b; }

2. Calling Functions

Once defined, you can call a function by using its name followed by parentheses, passing any required arguments:

void main() { int result = add(5, 3); print(result); // Outputs: 8 }

3. Function Parameters

Dart supports different types of parameters:

  • Required Positional Parameters: The default type, required and must be provided in the order defined.

    void greet(String name) { print('Hello, $name!'); }
  • Optional Positional Parameters: Enclosed in square brackets. They can be omitted when calling the function.

    void greet(String name, [String greeting = 'Hello']) { print('$greeting, $name!'); }
  • Named Parameters: Enclosed in curly braces and can be provided in any order.

    void greet({String name, String greeting = 'Hello'}) { print('$greeting, $name!'); }

4. Returning Values

Functions can return values using the return keyword. If no return type is specified, the default return type is void.

5. Anonymous Functions

Dart allows you to create functions without names, known as anonymous functions or lambda functions.

var list = [1, 2, 3]; var squared = list.map((number) => number * number).toList(); print(squared); // Outputs: [1, 4, 9]

6. Higher-Order Functions

Dart supports higher-order functions, which can take other functions as parameters or return them.

void main() { List<int> numbers = [1, 2, 3, 4]; var doubleNumbers = numbers.map(doubleValue); print(doubleNumbers); // Outputs: (2, 4, 6, 8) } int doubleValue(int value) { return value * 2; }

7. Recursion

Functions can call themselves, known as recursion. Be cautious with this approach to avoid infinite loops.

int factorial(int n) { if (n <= 1) return 1; return n * factorial(n - 1); }

8. Function Types

You can define a variable with a function type to store a function.

void main() { int Function(int, int) operation = add; print(operation(5, 3)); // Outputs: 8 }

Summary

Functions in Dart are powerful tools for organizing and managing code. By using different types of parameters, return types, and the ability to pass functions as arguments, you can create flexible and reusable code structures.