Skip to main content
The |= operator is a compound assignment operator in Dart that performs an OR (|) operation between the left and right operands and assigns the resulting value back to the left operand. Its behavior is dictated by the implementation of operator | on the left operand’s type.
a |= b;
While conceptually similar to a = a | b;, the compound assignment operator evaluates the left-hand side expression exactly once. This is a critical semantic distinction if the left operand is an expression with side effects, such as a mutating indexer or a function call. In a compound assignment, the side effect is triggered only once, whereas the expanded form would evaluate it twice.
// The index 'i' is incremented exactly once.
list[i++] |= b; 

// In contrast, the expanded form increments 'i' twice:
// list[i++] = list[i++] | b;

Built-in Type Mechanics

Integers (int) and BigInt (Bitwise OR) When applied to int or BigInt types, the operator performs a bitwise OR. It evaluates the binary representation of both operands, returning 1 for each bit position where at least one of the corresponding bits is 1. If both bits are 0, the resulting bit is 0. Platform-Specific Behavior for int:
  • Native Dart (Dart VM): Bitwise operations are evaluated as 64-bit integers.
  • Web Dart (Compiled to JavaScript): Bitwise operations truncate the operands to 32-bit integers prior to evaluation.
int a = 5;  // Binary representation: ...0101
int b = 3;  // Binary representation: ...0011

a |= b;     // Performs: 0101 | 0011
print(a);   // Outputs: 7 (Binary: ...0111)
Booleans (bool) (Non-Short-Circuiting Logical OR) When applied to bool types, |= invokes Dart’s non-short-circuiting logical OR (|). Unlike the standard || operator, which stops evaluation if the left operand is true, the | operator evaluates both the left and right operands. It assigns true to the left operand if at least one of the evaluated values is true.
bool a = false;
bool b = true;

a |= b; 
print(a);   // Outputs: true

Custom Types and Operator Overloading

Because Dart supports operator overloading, the |= operator is not restricted to primitive types. Any custom class can implement operator |, which automatically enables the |= compound assignment operator for instances of that class. For the assignment to be valid, the right operand must be of a type accepted by the left operand’s operator | signature, and the resulting return type must be assignable back to the left operand’s variable type.
class BitMask {
  final int value;
  
  BitMask(this.value);

  // Overriding the | operator automatically enables |=
  BitMask operator |(BitMask other) {
    return BitMask(this.value | other.value);
  }
}

void main() {
  BitMask mask1 = BitMask(4); // Binary: 0100
  BitMask mask2 = BitMask(2); // Binary: 0010

  mask1 |= mask2; 
  
  print(mask1.value); // Outputs: 6 (Binary: 0110)
}
Tired of Poor Dart Skills? Fix That With Deep Grasping!Learn More