If-Else in Dart Programming

Dart ProgrammingServer Side ProgrammingProgramming

If statements are a major part of any programming language as they allow us to run things based on certain conditions, that's why they come under the conditional statements category.

Dart's if-else statements follow the same syntax as Java's ones.

Syntax

if( condition ) {
   statement
}

If the condition in the above if parentheses evaluate to true, then the statements inside the code block will be evaluated.

Example

Consider the example shown below −

 Live Demo

void main() {
   var age = 10;
   if(age == 10){
      print("10 is perfect");
   }
}

Since in the above code the age == 10 evaluates to true, we get the code inside the code block of if executed.

Output

10 is perfect

Notice that if we change our age variable's value to something else, then nothing will be printed as output.

Example

Consider the example shown below −

void main() {
   var age = 11;
   if(age == 10){
      print("10 is perfect");
   }
}

Output

It won't print anything on the console.

To deal with cases like the above one, we make use of else clause that Dart also provides.

Example

Consider the example shown below −

 Live Demo

void main() {
   var age = 11;
   if(age == 10){
      print("10 is perfect");
   }else{
      print("Age not suitable");
   }
}

Output

Age not suitable

It also might be possible that we want to check whether the age is less than 10 and greater than 5 for some reason, for that case, we can make use of an else-if cause.

Example

Consider the example shown below −

 Live Demo

void main() {
   var age = 6;
   if(age == 10){
      print("10 is perfect");
   }else if(age < 10 && age > 5){
      print("Between 5 and 10!");
   }else{
      print("IDK bruh!");
   }
}

Output

Between 5 and 10!
raja
Updated on 21-May-2021 13:05:22

Advertisements