Overview
If statements allow you to execute code conditionally based on boolean expressions. Dart supports simple if statements, if-else statements, and nested conditionals.Basic Syntax
The basic structure of an if statement in Dart:If-Else Statement
An if-else statement provides two execution paths based on a condition:The condition must evaluate to a boolean value (
true or false). Dart does not allow non-boolean values in conditional expressions.Simple If Statement
You can use an if statement without an else clause when you only need to execute code when a condition is true:Nested If Statements
You can nest if statements to handle multiple conditions:Complete Example
Here’s a complete example demonstrating different types of if statements:Best Practices
Use else-if for readability
Instead of deeply nested if statements, use
else if chains for better code readability.Keep conditions simple
Break complex conditions into separate boolean variables with descriptive names.
Common Operators
| Operator | Description | Example | ||||
|---|---|---|---|---|---|---|
== | Equal to | x == 5 | ||||
!= | Not equal to | x != 5 | ||||
> | Greater than | x > 5 | ||||
< | Less than | x < 5 | ||||
>= | Greater than or equal | x >= 5 | ||||
<= | Less than or equal | x <= 5 | ||||
&& | Logical AND | x > 0 && x < 10 | ||||
| ` | ` | Logical OR | `x < 0 | x > 10` | ||
! | Logical NOT | !(x == 5) |