-1

I’m confused about when to use switch vs if in Dart. I want to know which one is better for specific situations and when to choose one over the other.

I tried using both if and switch to check a variable. I expected them to work the same, but I found that switch doesn’t handle certain conditions (like ranges or complex expressions) the way if does."

1
  • The switch statement only supports constant values, the if statement has no such restrictions. Commented Apr 22 at 11:20

2 Answers 2

1

if is perfect for checking conditions based on ranges or complex expressions, like if (x > 5 && x < 10) or if (score >= 90 && score <= 100).

if (x == 1) {
  // do something
} else if (x > 1 && x < 10) {
  // do something else
}

switch is great for situations where you are comparing a variable to multiple specific values, such as an enum or integer comparison. It's more readable and efficient when there are many possible values to check.

switch (status) {
  case Status.loading:
    // loading logic
    break;
  case Status.completed:
    // completed logic
    break;
  case Status.failed:
    // failed logic
    break;
  default:
    // default logic
}


Sign up to request clarification or add additional context in comments.

Comments

0

One thing to consider is that a switch can be determined to be "exhaustive", as in covering every possible value of a limited type like a bool or an enumor sealed classes. An equivalent series of if/else might not cover every case, leading to bad behavior.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.