Conditionals in Dart

Control program flow with if/else statements

Conditionals in Dart


Definition

Conditionals are control structures that allow your code to make decisions. They let you execute different code blocks based on whether a condition is true or false.


Comparison Operators


**Equality**

  • `==`: Equal to
  • `!=`: Not equal to

  • **Relational**

  • `>`: Greater than
  • `<`: Less than
  • `>=`: Greater than or equal to
  • `<=`: Less than or equal to

  • Conditional Statements


    **if Statement**

    Executes code only if a condition is true.

    `

    if (score >= 80) {

    print('Pass');

    }

    `

    **if-else Statement**

    Provides an alternative code block.

    `

    if (score >= 80) {

    print('Pass');

    } else {

    print('Fail');

    }

    `

    **if-else if-else Chain**

    Checks multiple conditions in order.

    `

    if (score >= 90) {

    print('A');

    } else if (score >= 80) {

    print('B');

    } else if (score >= 70) {

    print('C');

    } else {

    print('F');

    }

    `

    Logical Operators


  • `&&` (AND): Both conditions must be true
  • `||` (OR): At least one condition must be true
  • `!` (NOT): Reverses the condition
  • Cell2Dart
    // If-else if-else example int score = 85; if (score >= 90) { print('Grade: A'); } else if (score >= 80) { print('Grade: B'); } else if (score >= 70) { print('Grade: C'); } else { print('Grade: F'); }

    How Conditions Work


    1. **Evaluate**: Check if the condition is true or false

    2. **Branch**: Execute the matching code block

    3. **Continue**: Skip other blocks and continue


    When an if statement matches, the rest of the else-if and else blocks are skipped!

    Cell4Dart
    // Logical operators example int age = 25; bool isStudent = true; if (age >= 18 && isStudent) { print('Student discount available!'); } if (age < 13 || age >= 65) { print('Special pricing applies'); } if (!isStudent) { print('Not a student'); } else { print('You are a student'); }

    Practice

    CellcustomDart
    int age = 20; if (age >= 18) { print('Adult'); } else { print('Minor'); }
    Run code to see variables