What are Conditional Statements?
Conditional statements allow your program to make decisions based on certain conditions. They execute different blocks of code depending on whether a condition is true or false. Dart provides several ways to handle conditions: if, else if, else, switch, and the ternary operator.
- The
if Statement
if StatementThe if statement executes a block of code only if the specified condition evaluates to true.
- The
if-else Statement
if-else StatementThe if-else statement provides an alternative block of code to execute when the condition is false.
- The
else if Ladder
else if LadderWhen you have multiple conditions, you can chain them using else if. Only the first true condition's block is executed.
- Nested
if Statements
if StatementsYou can place if statements inside another if or else block to check more complex conditions.
- Ternary Operator (
condition ? expr1 : expr2)
condition ? expr1 : expr2)The ternary operator is a shorthand for simple if-else statements. It returns one of two expressions based on a condition.
- The
switch Statement
switch StatementThe switch statement is used when you need to compare a variable against many constant values. It's cleaner than a long else if ladder.
- The
switchexpression is evaluated once.
- The
- It is compared with each
caselabel using==.
- It is compared with each
- If a match is found, the corresponding block runs until a
breakis encountered.
- If a match is found, the corresponding block runs until a
- The
defaultcase is optional and runs if no case matches.
- The
- Switch with Enum
Using switch with enums is a common and powerful pattern in Dart. It ensures you handle all possible values.
- Null‑Aware Conditions
Dart provides special operators to handle nullable values in conditions:
?.: Safe member access (returns null if the object is null).
??: If‑null operator (returns left side if not null, else right side).
??=: Null‑aware assignment (assigns only if the variable is null).
Complete Example
Key Takeaways
- Use
if,else if,elsefor general conditional logic.
- Use
- The ternary operator
? :is a concise replacement for simpleif-else.
- The ternary operator
- Use
switchwhen comparing a variable against many constant values.
- Use
- Always include
breakin eachcase(except when intentionally falling through).
- Always include
- Enums work perfectly with
switchand ensure exhaustiveness.
- Enums work perfectly with
- Null‑aware operators help you handle nullable values safely in conditions.