Skip to main content
The collection if is a syntactic feature in Dart that enables the conditional inclusion of elements within collection literals (List, Set, and Map). It evaluates a boolean expression at runtime; if the expression resolves to true, the associated element (or entry) is added to the constructed collection. If false, the element is omitted.

Syntax

The syntax mimics a standard control flow if statement but lacks the enclosing braces {} typically used for block scope. It can also include an optional else clause.
// General Syntax
[
  element_A,
  if (condition) element_B,
  if (condition) element_C else element_D,
]

List and Set Implementation

When used within a List or Set literal, the operator controls the insertion of a single value.
final bool includeAdmin = true;
final bool isGuest = false;

// List Literal
final List<String> menu = [
  'Home',
  'Profile',
  if (includeAdmin) 'Admin Dashboard',
  if (isGuest) 'Sign Up' else 'Log Out',
];

// Result: ['Home', 'Profile', 'Admin Dashboard', 'Log Out']

Map Implementation

When used within a Map literal, the operator controls the insertion of a key-value entry.
final bool useSandbox = true;

// Map Literal
final Map<String, String> config = {
  'protocol': 'https',
  if (useSandbox) 'env': 'sandbox' else 'env': 'production',
};

// Result: {'protocol': 'https', 'env': 'sandbox'}

Composition with Spread Operators

Collection if can be composed with the spread operator (...) to conditionally insert multiple elements from another collection.
final bool hasOverrides = true;
final List<int> defaultValues = [1, 2];
final List<int> overrideValues = [10, 20];

final List<int> data = [
  0,
  if (hasOverrides) ...overrideValues else ...defaultValues,
  30
];

// Result: [0, 10, 20, 30]

Type Inference

Dart determines the static type of a collection literal by calculating the Least Upper Bound (LUB) of all elements, including those governed by if conditions. When a collection is assigned to an inferred variable (e.g., using var), the presence of conditional elements with differing types results in a broader inferred type, such as List<Object> or List<Object?>.
bool condition = true;

// Inferred as List<Object> because the LUB of int (1) and String ('a') is Object
var mixedList = [
  1, 
  if (condition) 'a'
]; 
Master Dart with Deep Grasping Methodology!Learn More