If Statement
The if statement is one of the most fundamental control structures in programming. It allows your program to make decisions and execute different blocks of code based on whether a condition is true or false.
Basic Syntax
The basic syntax of an if statement in Dart is:
if (condition) {
// Code to execute if condition is true
}
Think of it like a bouncer at a club - if you meet the requirements (condition is true), you get in (code executes). If not, you're turned away (code is skipped).
Simple Example
void main() {
int age = 18;
if (age >= 18) {
print("You are eligible to vote!");
}
}
In this example, since age is 18 and 18 >= 18 is true, the message will be printed.
Common Conditions
Here are some common types of conditions you can use:
| Operator | Description | Example |
|---|---|---|
== | Equal to | age == 18 |
!= | Not equal to | name != "John" |
> | Greater than | score > 90 |
< | Less than | price < 100 |
>= | Greater than or equal | age >= 21 |
<= | Less than or equal | speed <= 60 |
Logical Operators
You can combine multiple conditions using logical operators:
void main() {
int age = 25;
bool hasLicense = true;
if (age >= 18 && hasLicense) {
print("You can drive!");
}
if (age < 13 || age > 65) {
print("Special discount available!");
}
}
&&(AND): Both conditions must be true||(OR): At least one condition must be true!(NOT): Reverses the boolean value
Best Practices
- Use curly braces: Even for single statements, it's good practice to use braces for clarity
- Keep conditions simple: Complex conditions can be hard to read
- Use meaningful variable names: Makes your conditions self-documenting
// Good
if (isUserLoggedIn && hasPermission) {
// code here
}
// Less clear
if (a && b) {
// code here
}
The if statement is your gateway to making smart, responsive programs that can adapt to different situations!