Dart conditionals are identical to what you would find in C/C++ or Java, including the basic style of writing them.
Not only do you have your standard sex conditional operators, ==, !=, <. <=, >, >=, but the way you format the code is the same.
If Statement
You if statement is the if command, with your condition in parenthesis. The body of the if statement is contained within braces, as you see below in the example.
void main() {
int age = 36;
// this code will not run because 18 is greater than 36
if( age < 18 ) {
print("You are not yet an adult.");
}
if(age > 21) {
print("You can do almost anything you want...");
}
}
The body only executes if the if statement is true.
If – Else Statements
In Dart, as with most languages, you have an if-else statement. The if block is run if the condition is true, while the while block is run if the condition is false.
void main() {
int age = 36;
if( age < 18 ) {
// this code will not run because 18 is greater than 36
print("You are not yet an adult.");
} else {
// this code will run because 36 is greater than 18
print("You are an adult.");
}
}
Once again, you see the else body is enclosed by braces, and there has to be an if block for the corresponding else block.
Conditional Chaining
Additionally you can conditionally chain statements together through a series of if-else-if types of statements.
One nice thing about this, vs multiple if statements is that once a condition is met, you stop checking other conditions. This can make your code faster in some circumstances, depending upon where the condition is met.
void main() {
int age = 36;
if( age < 13 ) {
print("You are not yet an teenager.");
} else if( age < 18 ) {
print("You are not yet an adult.");
} else {
print("You are an adult.");
}
}
Dart Conditional Statements was originally found on Access 2 Learn
One Comment
Comments are closed.