flutter
/

Dart Conditions – If, Else, Switch and Conditional Expressions

Last Sync: Today

On this page

11
0%
5 min read
Remaining
5 minleft

Click any section to jump — progress syncs automatically

flutter

Dart Conditions – If, Else, Switch and Conditional Expressions

What are Conditional Statements?

Conditional statements allow your program to make decisions based on certain conditions. They execute different blocks of code depending on whether a condition is true or false. Dart provides several ways to handle conditions: if, else if, else, switch, and the ternary operator.

  1. The if Statement

The if statement executes a block of code only if the specified condition evaluates to true.

DARTRead-only
1
void main() {
  int age = 18;
  
  if (age >= 18) {
    print('You are eligible to vote.');
  }
}

  1. The if-else Statement

The if-else statement provides an alternative block of code to execute when the condition is false.

DARTRead-only
1
void main() {
  int age = 16;
  
  if (age >= 18) {
    print('You can vote.');
  } else {
    print('You are too young to vote.');
  }
}

  1. The else if Ladder

When you have multiple conditions, you can chain them using else if. Only the first true condition's block is executed.

DARTRead-only
1
void main() {
  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');
  }
}

  1. Nested if Statements

You can place if statements inside another if or else block to check more complex conditions.

DARTRead-only
1
void main() {
  int age = 20;
  bool hasID = true;
  
  if (age >= 18) {
    if (hasID) {
      print('You can enter the club.');
    } else {
      print('You need an ID.');
    }
  } else {
    print('You are too young.');
  }
}

  1. Ternary Operator (condition ? expr1 : expr2)

The ternary operator is a shorthand for simple if-else statements. It returns one of two expressions based on a condition.

DARTRead-only
1
void main() {
  int age = 20;
  String status = (age >= 18) ? 'Adult' : 'Minor';
  print(status); // Adult
}

  1. The switch Statement

The switch statement is used when you need to compare a variable against many constant values. It's cleaner than a long else if ladder.

    • The switch expression is evaluated once.
    • It is compared with each case label using ==.
    • If a match is found, the corresponding block runs until a break is encountered.
    • The default case is optional and runs if no case matches.
DARTRead-only
1
void main() {
  String grade = 'B';
  
  switch (grade) {
    case 'A':
      print('Excellent!');
      break;
    case 'B':
      print('Good job!');
      break;
    case 'C':
      print('Fair.');
      break;
    case 'D':
    case 'F':
      print('Need improvement.');
      break;
    default:
      print('Invalid grade.');
  }
}

  1. Switch with Enum

Using switch with enums is a common and powerful pattern in Dart. It ensures you handle all possible values.

DARTRead-only
1
enum TrafficLight { red, yellow, green }

void main() {
  TrafficLight light = TrafficLight.red;
  
  switch (light) {
    case TrafficLight.red:
      print('Stop');
      break;
    case TrafficLight.yellow:
      print('Caution');
      break;
    case TrafficLight.green:
      print('Go');
      break;
  }
}

  1. Null‑Aware Conditions

Dart provides special operators to handle nullable values in conditions:

    • ?. : Safe member access (returns null if the object is null).
    • ?? : If‑null operator (returns left side if not null, else right side).
    • ??= : Null‑aware assignment (assigns only if the variable is null).
DARTRead-only
1
void main() {
  String? name;
  
  // Using ?? to provide default value
  String displayName = name ?? 'Guest';
  print(displayName); // Guest
  
  // Using ?. for safe access
  print(name?.length); // null
}

Complete Example

DARTRead-only
1
void main() {
  int temperature = 25;
  
  // if-else chain
  if (temperature > 30) {
    print('It\'s hot!');
  } else if (temperature > 20) {
    print('Nice weather.');
  } else {
    print('It\'s cold.');
  }
  
  // Ternary
  String weather = (temperature > 25) ? 'Warm' : 'Cool';
  print(weather);
  
  // Switch with enum
  enum Day { monday, tuesday, wednesday, thursday, friday, saturday, sunday }
  Day today = Day.wednesday;
  
  switch (today) {
    case Day.saturday:
    case Day.sunday:
      print('Weekend!');
      break;
    default:
      print('Weekday.');
  }
}

Key Takeaways

    • Use if, else if, else for general conditional logic.
    • The ternary operator ? : is a concise replacement for simple if-else.
    • Use switch when comparing a variable against many constant values.
    • Always include break in each case (except when intentionally falling through).
    • Enums work perfectly with switch and ensure exhaustiveness.
    • Null‑aware operators help you handle nullable values safely in conditions.

Try it yourself

void main() {
  int number = 7;
  
  if (number % 2 == 0) {
    print('$number is even');
  } else {
    print('$number is odd');
  }
}

Test Your Knowledge

Q1
of 4

What is the output of this code? void main() { int x = 5; if (x > 3) print('A'); if (x > 7) print('B'); else print('C'); }

A
A
B
A C
C
B C
D
A B C
Q2
of 4

Which statement is best suited for checking a variable against many constant values?

A
if-else
B
switch
C
ternary operator
D
while loop
Q3
of 4

What is the value of `result` after executing `var result = (5 > 3) ? 'yes' : 'no';`?

A
yes
B
no
C
true
D
false
Q4
of 4

In a `switch` statement, what keyword is used to exit a case?

A
continue
B
exit
C
break
D
return

Frequently Asked Questions

Can I use `else if` without a final `else`?

Yes, the final else is optional. You can have an if followed by any number of else if blocks and no final else. If none of the conditions are true, no code in that chain will execute.

What's the difference between `if-else` and `switch`?

if-else is best for complex conditions involving ranges, logical operators, or different types. switch is ideal when you're comparing a single variable against many constant values, and it can be more readable and faster in such cases.

Can I use `switch` with strings?

Yes, Dart allows switch on strings, integers, and enums. For example, you can switch (dayString) { case 'Monday': ... }.

Is the ternary operator just a shorter `if-else`?

Yes, the ternary operator condition ? expr1 : expr2 is a concise way to return one of two values based on a condition. It's an expression, so it can be used inside larger expressions. However, for complex branching, prefer if-else for clarity.

How do null-aware operators help in conditions?

Null-aware operators like ?., ??, and ??= allow you to write concise code that handles nullable values without explicit if (x != null) checks. For example, x?.isEven returns null if x is null, and y ?? 0 provides a default value if y is null.

Can I have multiple conditions in a single `if` statement?

Yes, you can combine conditions using logical operators && (AND) and || (OR). For example: if (age >= 18 && hasID) { ... }.

Previous

dart operators

Next

dart loops

Related Content

Need help?

Explore our comprehensive docs or start a chat with our tech experts.