Function Basics

Functions are like little machines that take some input, do something with it, and give you back a result. Think of them as reusable blocks of code that help you organize your program and avoid repeating yourself!

What is a Function?

A function in Dart is a block of code that performs a specific task. You can call (or invoke) a function whenever you need to execute that task. Functions make your code more organized, readable, and maintainable.

Basic Function Syntax

Here's the basic structure of a function in Dart:

returnType functionName(parameters) {
  // function body
  return value; // optional
}

Simple Function Example

Let's start with a simple function that greets someone:

void greetUser(String name) {
  print('Hello, $name! Welcome to Dart programming!');
}

void main() {
  greetUser('Alice');  // Output: Hello, Alice! Welcome to Dart programming!
  greetUser('Bob');    // Output: Hello, Bob! Welcome to Dart programming!
}

Functions with Return Values

Functions can return values using the return keyword:

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

double calculateArea(double length, double width) {
  return length * width;
}

void main() {
  int sum = addNumbers(5, 3);
  print('Sum: $sum');  // Output: Sum: 8
  
  double area = calculateArea(4.5, 2.0);
  print('Area: $area');  // Output: Area: 9.0
}

Functions Without Parameters

You can also create functions that don't need any input:

String getCurrentDay() {
  return 'Today is a great day to code!';
}

void showWelcomeMessage() {
  print('Welcome to our Dart course!');
  print('Let\'s learn functions together!');
}

void main() {
  String message = getCurrentDay();
  print(message);
  
  showWelcomeMessage();
}

Return Types

Return TypeDescriptionExample
voidFunction doesn't return anythingvoid printMessage() { ... }
intReturns an integerint getAge() { return 25; }
StringReturns a stringString getName() { return 'John'; }
doubleReturns a decimal numberdouble getPrice() { return 19.99; }
boolReturns true or falsebool isValid() { return true; }

Why Use Functions?

  1. Reusability: Write once, use many times
  2. Organization: Keep your code neat and structured
  3. Maintainability: Easy to update and fix bugs
  4. Readability: Makes your code easier to understand

Think of functions like recipes in a cookbook - once you write the recipe (function), you can use it whenever you want to make that dish (call the function)!

Key Points to Remember

  • Every function has a name and can have parameters
  • Use void when your function doesn't return anything
  • Use specific types (int, String, etc.) when your function returns a value
  • Function names should be descriptive and follow camelCase convention
  • The main() function is special - it's where your program starts running