Skip to main content
The else keyword designates an alternative execution path within a conditional control flow statement. It introduces a clause that executes a statement or block of code exclusively when the boolean expression of the immediately preceding if statement evaluates to false.

Standard Control Flow syntax

In a standard statement context, else follows an if block. The associated code block is mutually exclusive to the if block; exactly one of the two will execute.
if (booleanExpression) {
  // Executes when booleanExpression is true
} else {
  // Executes when booleanExpression is false
}

Chained Conditionals (else if)

The else keyword can be immediately followed by another if statement to form a chain of conditional checks. The Dart runtime evaluates these conditions sequentially from top to bottom. The first branch with a true condition executes, and all subsequent branches—including the final trailing else—are skipped.
if (conditionA) {
  // Executes if conditionA is true
} else if (conditionB) {
  // Executes if conditionA is false AND conditionB is true
} else {
  // Executes if both conditionA and conditionB are false
}

Collection Context (Collection If)

Dart supports if and else within collection literals (lists, sets, and maps) to conditionally include elements. In this context, else determines which element is inserted into the collection when the condition is false.
var nav = [
  'Home',
  'Settings',
  if (isAdmin) 'Admin Dashboard' else 'User Profile'
];

Scoping Rules

The else clause introduces a new lexical scope. Variables defined inside the preceding if block are not accessible within the else block, and vice versa.
if (isValid) {
  var id = 100; // 'id' is local to this block
} else {
  // 'id' is not accessible here
  var error = 'Invalid'; // 'error' is local to this block
}

Dangling Else

Dart resolves the “dangling else” ambiguity by binding an else clause to the nearest preceding if statement that does not already have an else clause, respecting block nesting.
if (conditionA)
  if (conditionB)
    statementB();
  else
    statementC(); // Binds to "if (conditionB)"
To bind the else to the outer if, braces must be used to explicitly define the scope:
if (conditionA) {
  if (conditionB)
    statementB();
} else {
  statementC(); // Binds to "if (conditionA)"
}
Master Dart with Deep Grasping Methodology!Learn More