Conditions in Dart
Conditions In Dart
When a certain condition is true, you need to execute a certain code. In such situations, you can use conditions in Dart. For E.g, if a student score more than 90 marks then he got grade A.
Types Of Condition
- If Condition
- If-Else Condition
- If-Else-If Condition
- Switch case
If Condition
It is used when you have to execute statements when certain condition is true.
Syntax
if(condition) {
Statement 1;
Statement 2;
.
.
Statement n;
}
Example Of If Condition
It prints whether the person is voter. If the person age is greater and equal to 18, it will print, You are voter.
void main()
{
var age = 20;
if(age >= 18){
print("You are voter.");
}
}
If-Else Condition
If the result of the condition is true, then body of if-condition is executed, otherwise body of else-condition will be executed.
Syntax
if(condition){
statements;
}else{
statements;
}
Example Of If-Else Condition
It prints whether the person is voter or not.
void main()
{
int age = 12;
if(age >= 18){
print("You are voter.");
}else{
print("You are not voter.");
}
}
If-Else-If Condition
When you have multiple if conditions, then you can use if-else-if. You can learn more in example below.
Syntax
if(condition1){
statements1;
}else if(condition2){
statements2;
}else if(condition3){
statements3;
}
.
.
.
else(conditionN){
statementsN;
}
Example Of If-Else-If Condition
void main() {
int noOfMonth = 5;
// Check the no of month
if (noOfMonth == 1) {
print("The month is jan");
} else if (noOfMonth == 2) {
print("The month is feb");
} else if (noOfMonth == 3) {
print("The month is march");
} else if (noOfMonth == 4) {
print("The month is april");
} else if (noOfMonth == 5) {
print("The month is may");
} else if (noOfMonth == 6) {
print("The month is june");
} else if (noOfMonth == 7) {
print("The month is july");
} else if (noOfMonth == 8) {
print("The month is aug");
} else if (noOfMonth == 9) {
print("The month is sep");
} else if (noOfMonth == 10) {
print("The month is oct");
} else if (noOfMonth == 11) {
print("The month is nov");
} else if (noOfMonth == 12) {
print("The month is dec");
} else {
print("Invalid option given.");
}
}
Find Greatest Number Among 3 Numbers.
void main()
{
int num1 = 1200;
int num2 = 1000;
int num3 = 150;
if(num1 > num2 && num1 > num3){
print("Num 1 is greater: i.e $num1");
}
if(num2 > num1 && num2 > num3){
print("Num2 is greater: i.e $num2");
}
if(num3 > num1 && num3 > num2){
print("Num3 is greater: i.e $num3");
}
}
Assert
It will take conditions as an argument. If the condition is true, nothing happens. If a condition is false, it will raise an error.
Syntax
assert(condition);
void main() {
var age = 22;
assert(age!=22);
}
Note: The assert(condition)
method only runs in development mode. It will throw an exception only when the condition is false. If the condition is true, nothing happens. Production code ignores it.