Dart Functions

Reusable blocks of code in Dart

🔧 What are Functions?

Functions are reusable blocks of code that perform specific tasks. They help organize code, avoid repetition, and make programs easier to understand and maintain in Dart applications.


// Simple function example
void sayHello() {
  print('Hello, World!');
}

sayHello(); // Call the function
                                    

Function Types

📝

Void Functions

Functions that don't return values

void greet() {
  print('Hello!');
}
â†Šī¸

Return Functions

Functions that return values

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

Arrow Functions

Short syntax for simple functions

int multiply(int a, int b) => a * b;
🔄

Anonymous Functions

Functions without names

var square = (int x) => x * x;

🔹 Basic Function Syntax

Understanding the structure of Dart functions:

// Function structure:
// returnType functionName(parameters) {
//   // function body
//   return value; // if needed
// }

void main() {
  // Void function - no return value
  void printMessage() {
    print('This is a message');
  }
  
  // Function with return value
  String getName() {
    return 'John Doe';
  }
  
  // Call functions
  printMessage();
  String name = getName();
  print('Name: $name');
}

Output:

This is a message
Name: John Doe

🔹 Functions with Parameters

Functions can accept input values called parameters:

void main() {
  // Function with one parameter
  void greetPerson(String name) {
    print('Hello, $name!');
  }
  
  // Function with multiple parameters
  int calculateSum(int a, int b) {
    return a + b;
  }
  
  // Function with different parameter types
  void displayInfo(String name, int age, bool isStudent) {
    print('Name: $name, Age: $age, Student: $isStudent');
  }
  
  // Call functions with arguments
  greetPerson('Alice');
  int result = calculateSum(10, 20);
  print('Sum: $result');
  displayInfo('Bob', 25, true);
}

Output:

Hello, Alice!
Sum: 30
Name: Bob, Age: 25, Student: true

🔹 Arrow Functions

Shorter syntax for simple functions:

void main() {
  // Regular function
  int addRegular(int a, int b) {
    return a + b;
  }
  
  // Arrow function (same as above)
  int addArrow(int a, int b) => a + b;
  
  // More arrow function examples
  String getFullName(String first, String last) => '$first $last';
  bool isEven(int number) => number % 2 == 0;
  double calculateArea(double radius) => 3.14159 * radius * radius;
  
  // Using the functions
  print('Regular: ${addRegular(5, 3)}');
  print('Arrow: ${addArrow(5, 3)}');
  print('Full name: ${getFullName('John', 'Smith')}');
  print('Is 4 even? ${isEven(4)}');
  print('Circle area: ${calculateArea(5.0)}');
}

Output:

Regular: 8
Arrow: 8
Full name: John Smith
Is 4 even? true
Circle area: 78.53975

🔹 Anonymous Functions

Functions without names, often used with collections:

void main() {
  // Anonymous function stored in variable
  var multiply = (int a, int b) => a * b;
  print('Multiply: ${multiply(4, 5)}');
  
  // Anonymous functions with lists
  List numbers = [1, 2, 3, 4, 5];
  
  // Using forEach with anonymous function
  print('Numbers:');
  numbers.forEach((number) => print('  $number'));
  
  // Using map with anonymous function
  var doubled = numbers.map((n) => n * 2).toList();
  print('Doubled: $doubled');
  
  // Using where with anonymous function
  var evens = numbers.where((n) => n % 2 == 0).toList();
  print('Even numbers: $evens');
}

Output:

Multiply: 20
Numbers:
1
2
3
4
5
Doubled: [2, 4, 6, 8, 10]
Even numbers: [2, 4]

🔹 Function Best Practices

Good Function Design:

  • Single Purpose: Each function should do one thing well
  • Clear Names: Use descriptive function names
  • Reasonable Length: Keep functions short and focused
  • Consistent Style: Follow Dart naming conventions

Function Naming:

  • camelCase: Use camelCase for function names
  • Verbs: Start with action words (get, set, calculate, check)
  • Descriptive: Make the purpose clear from the name
// Good function examples
bool isValidEmail(String email) => email.contains('@');
double calculateTax(double amount, double rate) => amount * rate;
String formatCurrency(double amount) => '\$${amount.toStringAsFixed(2)}';

void main() {
  print('Valid email: ${isValidEmail('[email protected]')}');
  print('Tax: ${calculateTax(100.0, 0.08)}');
  print('Formatted: ${formatCurrency(123.456)}');
}

🧠 Test Your Knowledge

What is the arrow function syntax for a function that returns a + b?