loading...
Cover image for Switch case in Dart

Switch case in Dart

jay_tillu profile image Jay Tillu😎 ・2 min read
  • A switch statement is an alternative of else if statements which allows a variable to be tested for equality against a list of values.

  • Each value is called a case, and the variable being switched on is checked for each switch case.

  • Wherever an expression value matches with a case value, the body of that case will be executed.

  • The switch will be terminated using a break statement. Here break statement is compulsory. Otherwise, the dart analysis engine will throw a syntax error.

  • Only for the default case break is optional. Otherwise, in all cases break is compulsory.

Syntax


switch (expression) {
  case ONE:
    {
      statement(s);
    }
  break;

  case TWO:
    {
      statement(s);
    }
  break;

  default:
    {
      statement(s);
    }
}

Rules of the Switch Case

  • The default case is optional.

  • All case expression must be unique.
    The case statements can include only constants. It cannot be a variable or an expression.

  • The data type of the variable and the case expression must match.

  • There can be any number of case statements within a switch.

Sample Code


void main() {
  var grade = "A";

  switch (grade) {
    case "A":
      {
        print("Excellent");
      }
      break;

    case "B":
      {
        print("Good");
      }
      break;

    case "C":
      {
        print("Fair");
      }
      break;

    case "D":
      {
        print("Poor");
      }
      break;

    default:
      {
        print("Invalid choice");
      }
      break;
  }
}

So, guys, That’s all you need to know about switch case. Please let me know if I miss something. I’ll happy to learn from you. Till Then Keep Loving, Keep Coding. I’ll surely catch you up in the next article.

Remember no teacher, no book, no video tutorial, or no blog can teach you everything. As one said Learning is Journey and Journey never ends. Just collect some data from here and there, read it, learn it, practice it, and try to apply it. Don’t feel hesitate that you can’t do that or you don’t know this concept or that concept. Remember every programmer was passed from the path on which you are walking right now. Remember Every Master was Once a Beginner. Work hard and Give your best.

For More Information Please Visit Following Links

Wanna get in touch with me? Here are links. I’ll love to become your friend. 😊
Twitter
Facebook
Instagram
Medium
or just mail me at jayviveki13@gmail.com

Posted on by:

jay_tillu profile

Jay Tillu😎

@jay_tillu

🌏 विधायास्य धमॅस्य संरक्षणम् 🌍 ☀️ Society before Self ☀️ 🙏🏻 Humanism by Religion 🙏🏻 💻 Work for Mankind 💻 🌐 Believes in वसुधैव कुटुम्बकम् 🌐

Discussion

pic
Editor guide