3.1conditions in Dart
3.1conditions in Dart
When you write a computer program, you need to be able to tell the computer
what to do in different situations. With conditions, you can control the flow of the
dart program. Suppose you need to execute a specific code when a particular
situation is true. In that case, you can use conditions in Dart. E.g., a calculator
app must perform subtraction if the user presses the subtract button and addition
if the user taps the add button.
Types Of Condition
If Condition
The easy and most common way of controlling the flow of a program is through
the use of an if statement. If statement allow us to execute a code block when the
given condition is true. Conditions evaluate boolean values.
Syntax
if(condition) {
Statement 1;
Statement 2;
.
.
Statement n;
}
Eg:
void main()
{
var age = 20;
If-Else Condition
If the result of the condition is true, then the body of the if-condition is executed.
Otherwise, the body of the else-condition is executed.
Syntax
if(condition){
statements;
}else{
statements;
}
Dart program prints whether the person is a voter or not based on age.
void main(){
int age = 12;
if(age >= 18){
print("You are voter.");
}else{
print("You are not voter.");
}
}
Condition Based On Boolean Value
void main(){
bool isMarried = false;
if(isMarried){
print("You are married.");
}else{
print("You are single.");
}
}
If-Else-If Condition
When you have multiple if conditions, then you can use if-else-if. You can learn
more in the example below. When you have more than two conditions, you can
use if, else if, else in dart.
Syntax
if(condition1){
statements1;
}else if(condition2){
statements2;
}else if(condition3){
statements3;
}
.
.
.
else(conditionN){
statementsN;
}
This program prints the month name based on the numeric value of that month.
You will get a different result if you change the number of month.
void main() {
int noOfMonth = 5;
void main(){
int num1 = 1200;
int num2 = 1000;
int num3 = 150;