Dart

Dart if-else Statement

Dart if-else Statement

In this tutorial, we will learn about the Dart if-else statement. The if condition can be true or false. The if-else statement allows us to specify code blocks for both the condition’s results. If the given condition evaluates to true, then the if code block is executed, and if the given condition evaluates to false, then the else code block is executed.

Dart if-else Syntax

The general syntax of the if-else statement in Dart is as follows:
 if(condition) {
  // if code statement(s);
 } else{
  // else code statement(s);
  }
The if code block is executed when the given condition is true. If the given condition is false, the else code block is executed.

Example

Let’s understand the concept with an example.
/*
Dart if-else statement demo
Dart Tutorials - www.TestingDocs.com
*/

void main() {
int a=9; int b=7;
print("Before: if-else statement");
if(a>b){
   print("a is greater than b");
} else {
   print("a is less or equal to b");
};
print("After: if-else statement");

}

Dart Program Output

Before: if-else statement
a is greater than b
After: if-else statement

 

Dart if-else Statement

Explanation

Test case 1

In the above program code, we have declared two integer variables a and b. The variable a holds 9 and the variable b holds 7 values.

Here, the if condition (a > b) is a Boolean expression that evaluates to either true or false. If the condition is true, the code block inside the if statement is executed. If the condition is false, the code block inside the else statement is executed. Since 9 > 7 the boolean expression or the condition a > b
evaluates to true. The if block is executed.

Test case 2

To execute the else block store a value greater than the variable a in the variable b. Run the Dart program in the IDE.

In the above example, we have used only one if-else statement. However, we can also have multiple if-else statements nested inside each other or use else-if clauses to handle multiple conditions.

 

Dart Tutorials

Dart tutorial on this website can be found at:

More information on Dart:

  • https://dart.dev/