Skip to main content
The if statement is a control flow structure that conditionally executes a statement or block of code based on the evaluation of a boolean expression. Dart requires the condition to be strictly of type bool; unlike dynamically typed languages, values such as 1, 0, or non-null objects are not implicitly coerced to true or false.

Standard Syntax

The basic syntax evaluates a condition inside parentheses. If the condition evaluates to true, the code inside the braces executes.
if (condition) {
  // Executes if condition is true
}

If-Else and Else-If

To handle false evaluations or multiple conditions, else and else if clauses are chained to the initial statement.
if (conditionA) {
  // Executes if conditionA is true
} else if (conditionB) {
  // Executes if conditionA is false and conditionB is true
} else {
  // Executes if all preceding conditions are false
}

Scope and Type Promotion

Dart’s flow analysis integrates with the if statement to enable type promotion. If a local variable is checked against a specific type or nullability within an if condition, Dart promotes the variable to that more specific type within the associated block.
void handleInput(Object input) {
  // Flow analysis determines 'input' is a String inside this block
  if (input is String) {
    print(input.length); // .length is valid because input is promoted to String
  }
}

Conditional Expressions

Dart supports the ternary operator for concise conditional assignment. This evaluates a condition and returns one of two expressions. Syntax: condition ? expressionIfTrue : expressionIfFalse
var visibility = isPublic ? 'visible' : 'hidden';

Collection If

Dart includes a specialized “collection if” that allows the conditional inclusion of elements within list, set, and map literals. This is syntactically distinct from the statement-level if. List/Set Context:
var navItems = [
  'Home',
  'Profile',
  if (isAdmin) 'Admin Dashboard', // Adds element only if isAdmin is true
];
Map Context:
var config = {
  'theme': 'dark',
  if (enableLogging) 'logLevel': 'verbose', // Adds entry only if enableLogging is true
};

Guard Clauses (Switch Context)

While distinct from the standard if statement, Dart switch cases can utilize when clauses to evaluate boolean conditions before executing a case body.
switch (pair) {
  case (int a, int b) when a > b:
    print('First element is larger');
  // ...
}
Master Dart with Deep Grasping Methodology!Learn More