|= 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 = 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.
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.
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.
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.
Tired of Poor Dart Skills? Fix That With Deep Grasping!Learn More





