Dart If...Else

Making decisions in your Dart programs

🤔 What is If...Else?

If-else statements allow your program to make decisions by executing different code blocks based on conditions. It's like asking questions and taking different actions based on the answers.


// Simple if-else example
void main() {
  int temperature = 25;
  if (temperature > 30) {
    print('It\'s hot outside!');
  } else {
    print('It\'s pleasant weather.');
  }
}
                                    

Types of If Statements

Simple If

Execute code when condition is true

if (age >= 18) {
  print('You can vote');
}
⚖️

If-Else

Choose between two options

if (score >= 50) {
  print('Pass');
} else {
  print('Fail');
}
🔗

Else If

Multiple conditions to check

if (grade >= 90) {
  print('A');
} else if (grade >= 80) {
  print('B');
} else {
  print('C');
}
🎯

Ternary Operator

Short form for simple conditions

String result = age >= 18 
  ? 'Adult' 
  : 'Minor';

🔹 Basic If Statement

The simplest form checks one condition:

void main() {
  int number = 10;
  
  if (number > 0) {
    print('Number is positive');
  }
  
  print('Program continues...');
}

Output:

Number is positive

Program continues...

🔹 If-Else Statement

Choose between two different actions:

void main() {
  int age = 16;
  
  if (age >= 18) {
    print('You are eligible to vote');
  } else {
    print('You are not eligible to vote yet');
  }
}

Output:

You are not eligible to vote yet

🔹 Multiple Conditions (Else If)

Check multiple conditions in sequence:

void main() {
  int marks = 85;
  
  if (marks >= 90) {
    print('Grade: A+');
  } else if (marks >= 80) {
    print('Grade: A');
  } else if (marks >= 70) {
    print('Grade: B');
  } else if (marks >= 60) {
    print('Grade: C');
  } else {
    print('Grade: F');
  }
}

Output:

Grade: A

🔹 Logical Operators

Combine multiple conditions using logical operators:

void main() {
  int age = 25;
  bool hasLicense = true;
  
  // AND operator (&&)
  if (age >= 18 && hasLicense) {
    print('You can drive');
  }
  
  // OR operator (||)
  if (age < 16 || age > 65) {
    print('Special driving rules may apply');
  }
  
  // NOT operator (!)
  if (!hasLicense) {
    print('You need a license to drive');
  }
}

Output:

You can drive

🔹 Ternary Operator

A shorthand way to write simple if-else statements:

void main() {
  int number = 15;
  
  // Traditional if-else
  String result1;
  if (number % 2 == 0) {
    result1 = 'Even';
  } else {
    result1 = 'Odd';
  }
  
  // Ternary operator (shorter)
  String result2 = number % 2 == 0 ? 'Even' : 'Odd';
  
  print('Number is: $result2');
}

Output:

Number is: Odd

🧠 Test Your Knowledge

What is the correct syntax for an if-else statement in Dart?