If Statement

The if statement is one of the most fundamental control structures in programming. It allows your program to make decisions and execute different blocks of code based on whether a condition is true or false.

Basic Syntax

The basic syntax of an if statement in Dart is:

if (condition) {
  // Code to execute if condition is true
}

Think of it like a bouncer at a club - if you meet the requirements (condition is true), you get in (code executes). If not, you're turned away (code is skipped).

Simple Example

void main() {
  int age = 18;
  
  if (age >= 18) {
    print("You are eligible to vote!");
  }
}

In this example, since age is 18 and 18 >= 18 is true, the message will be printed.

Common Conditions

Here are some common types of conditions you can use:

OperatorDescriptionExample
==Equal toage == 18
!=Not equal toname != "John"
>Greater thanscore > 90
<Less thanprice < 100
>=Greater than or equalage >= 21
<=Less than or equalspeed <= 60

Logical Operators

You can combine multiple conditions using logical operators:

void main() {
  int age = 25;
  bool hasLicense = true;
  
  if (age >= 18 && hasLicense) {
    print("You can drive!");
  }
  
  if (age < 13 || age > 65) {
    print("Special discount available!");
  }
}
  • && (AND): Both conditions must be true
  • || (OR): At least one condition must be true
  • ! (NOT): Reverses the boolean value

Best Practices

  1. Use curly braces: Even for single statements, it's good practice to use braces for clarity
  2. Keep conditions simple: Complex conditions can be hard to read
  3. Use meaningful variable names: Makes your conditions self-documenting
// Good
if (isUserLoggedIn && hasPermission) {
  // code here
}

// Less clear
if (a && b) {
  // code here
}

The if statement is your gateway to making smart, responsive programs that can adapt to different situations!