Skip to main content
The /= operator is a compound assignment operator that divides the variable on the left-hand side (LHS) by the expression on the right-hand side (RHS) and assigns the result back to the LHS variable.

Syntax

variable /= expression;

Operational Semantics

The /= operator invokes the division operator (/) defined on the LHS operand. The operation a /= b is equivalent to assigning the result of a / b to a, with the specific constraint that the LHS expression a is evaluated exactly once. This distinction is critical for expressions involving side effects. For example, in the expression list[i++] /= 2, the index i is incremented only once. If expanded manually to list[i++] = list[i++] / 2, the index would be incremented twice, resulting in incorrect logic.

Type Constraints and Behavior

The validity of the /= operation depends on the return type of the / operator defined by the LHS operand’s type. The return type of the division must be assignable to the static type of the LHS variable.

Built-in Numeric Types

For Dart’s built-in numeric types (int and double), the standard / operator always returns a double. Consequently, the LHS variable must be of a type that can hold a double. Valid types include double, num (the supertype of double), and dynamic. Attempting to use /= on a variable statically typed as int results in a compile-time error because the resulting double cannot be assigned to an int.
// Valid: LHS is double
double x = 10.0;
x /= 2; // x becomes 5.0

// Valid: LHS is num (can hold double)
num n = 10;
n /= 2; // n becomes 5.0 (type is now double at runtime)

// Invalid: LHS is int
int y = 10;
y /= 2; // Error: A value of type 'double' can't be assigned to a variable of type 'int'.

User-Defined Types

Dart allows operator overloading. If a user-defined class implements the / operator, /= can be used on instances of that class. The operation is valid only if the return type of the user-defined / operator is assignable to the variable’s type.
class Vector {
  final int x, y;
  Vector(this.x, this.y);

  // The / operator returns a Vector, making /= valid for Vector types
  Vector operator /(num divisor) {
    return Vector((x / divisor).round(), (y / divisor).round());
  }
}

void main() {
  Vector v = Vector(10, 20);
  v /= 2; // Valid: v becomes Vector(5, 10)
}
Master Dart with Deep Grasping Methodology!Learn More