Dart Functions and Control Flow

Functions let you group reusable code. Control flow — if/else, loops, and switch — lets your program make decisions. Together they form the logic behind every app feature.

What Is a Function

A function is a named block of code that performs a task. You write it once and call it as many times as needed.

  ┌──────────────────────────────┐
  │  FUNCTION: greetUser         │
  │  Input: name (String)        │
  │  Task: builds a greeting     │
  │  Output: "Hello, Ravi!"      │
  └──────────────────────────────┘

Defining a Function in Dart

// Basic function with no return value
void sayHello() {
  print('Hello!');
}

// Function with a parameter
void greetUser(String name) {
  print('Hello, $name!');
}

// Function that returns a value
int addNumbers(int a, int b) {
  return a + b;
}

// Calling the functions
sayHello();
greetUser('Ravi');
int result = addNumbers(5, 3);  // result = 8

Return Types

The word before the function name tells Dart what type the function returns. Use void when the function returns nothing.

  void   → returns nothing
  int    → returns a whole number
  String → returns text
  bool   → returns true or false
  double → returns a decimal number

Named and Optional Parameters

Named Parameters

Named parameters make function calls more readable. Wrap them in curly braces.

void createProfile({required String name, int age = 18}) {
  print('$name is $age years old');
}

createProfile(name: 'Ananya', age: 25);
createProfile(name: 'Karan');  // age defaults to 18

Positional Optional Parameters

void displayScore(int score, [String? grade]) {
  print('Score: $score, Grade: ${grade ?? 'N/A'}');
}

displayScore(85, 'A');
displayScore(72);  // grade is null

Arrow Functions

When a function has only one line, use an arrow (=>) to shorten it.

// Regular
int square(int n) {
  return n * n;
}

// Arrow version (same thing)
int square(int n) => n * n;

Control Flow — If / Else

If/else lets your app choose different paths based on a condition.

  Condition TRUE  → run block A
  Condition FALSE → run block B

  ┌──────────────┐
  │  score ≥ 50? │
  └──────┬───────┘
         │
    ┌────┴─────┐
   YES         NO
    │           │
  [PASS]     [FAIL]
int score = 65;

if (score >= 50) {
  print('Passed');
} else if (score >= 75) {
  print('Distinction');
} else {
  print('Failed');
}

Control Flow — Switch

Use switch when you check one variable against many possible values.

String day = 'Monday';

switch (day) {
  case 'Monday':
    print('Start of the week');
    break;
  case 'Friday':
    print('Almost weekend');
    break;
  default:
    print('Regular day');
}

Loops in Dart

For Loop

for (int i = 1; i <= 5; i++) {
  print('Item $i');
}
// Prints: Item 1, Item 2, Item 3, Item 4, Item 5

While Loop

int count = 0;
while (count < 3) {
  print('Count: $count');
  count++;
}

For-Each Loop

List<String> fruits = ['Apple', 'Mango', 'Banana'];

for (String fruit in fruits) {
  print(fruit);
}

Loop Diagram

  for loop:
  ─────────────────────────────────
  Start (i=1) → Check (i ≤ 5)? → Run body → i++ → Check again...
                      │
                      NO → Exit loop

Break and Continue

for (int i = 1; i <= 10; i++) {
  if (i == 4) continue;  // Skip 4
  if (i == 7) break;     // Stop at 7
  print(i);
}
// Output: 1, 2, 3, 5, 6

Anonymous Functions and Closures

Dart supports anonymous functions — functions without names, often used as arguments.

List<int> numbers = [3, 1, 4, 1, 5];

numbers.forEach((num) {
  print(num * 2);
});

// Shorter with arrow
numbers.forEach((num) => print(num * 2));

Functions Inside Flutter

In Flutter apps, you use functions constantly — for button actions, data processing, and building widget trees.

ElevatedButton(
  onPressed: () {
    // This anonymous function runs when button is tapped
    print('Button tapped!');
  },
  child: Text('Click Me'),
)

Leave a Comment

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