Functions in Dart

Learn how functions work and how the call stack tracks execution

Functions in Dart


Definition

A function is a reusable block of code that performs a specific task. Functions help you organize code, reduce duplication, and make programs easier to understand and maintain.


Function Syntax

`

returnType functionName(parameterType parameterName) {

// Function body

return value;

}

`

Key Components


Return Type

  • Specifies what type of value the function returns
  • Use `void` if the function returns nothing
  • Examples: `int`, `String`, `double`, `bool`

  • Parameters

  • Input values passed to a function
  • Each parameter has a type and name
  • A function can have zero or multiple parameters

  • Function Call

  • When you use a function, you "call" it
  • Pass arguments (actual values) that match the parameters
  • The function executes and returns a result
  • Cell2Dart
    // Simple function with parameters and return value int add(int a, int b) { return a + b; } // Call the function int result = add(5, 3); print('5 + 3 = $result'); // Another example String greet(String name) { return 'Hello, $name!'; } String message = greet('Dart'); print(message);

    Understanding the Call Stack


    When a function is called:

    1. **Push**: The function is added to the call stack

    2. **Execute**: The function body runs

    3. **Return**: The function returns a value

    4. **Pop**: The function is removed from the stack


    The **call stack** (shown on the right) shows which functions are currently running. When main() calls add(), add() appears on top of the stack. When add() finishes, it's removed.

    Cell4Dart
    // Function calling another function int multiply(int a, int b) { return a * b; } int calculate(int x, int y) { int product = multiply(x, y); return product + 10; } int result = calculate(3, 4); print('Result: $result');

    Void Functions

    Functions that don't return a value use the `void` return type. They perform an action but don't send data back.


    Function Benefits

  • **Reusability**: Write once, use many times
  • **Readability**: Code is organized and easier to understand
  • **Maintainability**: Changes in one place affect all uses
  • **Testing**: Individual functions can be tested separately
  • Cell6Dart
    // Function with no return value (void) void printMultipleTimes(String message, int times) { for (int i = 0; i < times; i++) { print(message); } } printMultipleTimes('Dart', 3);

    Practice

    CellcustomDart
    void greet(String name) { print('Hello, $name!'); } greet('Dart');
    Run code to see variables and call stack