Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

The -- operator is a unary arithmetic decrement operator in Dart that subtracts exactly 1 from its numeric operand. It mutates the underlying variable in place and requires the operand to be a non-final, non-const variable. The operator functions in two distinct evaluation contexts based on its placement relative to the operand: prefix and postfix.

Prefix Decrement (--var)

In the prefix position, the operator performs a pre-decrement. Dart subtracts 1 from the operand before evaluating the expression. The expression resolves to the newly decremented value.
int a = 5;
int b = --a; 

// Evaluation sequence:
// 1. a is decremented by 1 (a becomes 4)
// 2. The expression resolves to the new value of a (4)
// 3. b is assigned 4

Postfix Decrement (var--)

In the postfix position, the operator performs a post-decrement. Dart evaluates the expression using the current value of the operand, and subtracts 1 from the operand after the evaluation is complete.
int x = 5;
int y = x--; 

// Evaluation sequence:
// 1. The expression resolves to the current value of x (5)
// 2. y is assigned 5
// 3. x is decremented by 1 (x becomes 4)

Technical Constraints and Behavior

  • Type Requirements: The operand must be of type num (int or double), or a custom class that implements the - operator.
  • Immutability: Applying -- to a final or const variable results in a compile-time error, as the operator fundamentally requires reassignment.
  • Desugaring: Dart does not allow direct overriding of the -- operator. Instead, the Dart compiler treats a-- or --a as syntactic sugar for a = a - 1.
  • Custom Classes: Because of the desugaring mechanism, if you want to use the -- operator on an instance of a custom class, you must override the binary - operator. The class must also be assigned to a mutable variable (var or explicit type, not final).
class Counter {
  final int value;
  Counter(this.value);

  // Overriding the binary '-' operator enables the '--' operator
  Counter operator -(int amount) => Counter(value - amount);
}

void main() {
  Counter c = Counter(10);
  c--; // Implicitly executes: c = c - 1;
}
Master Dart with Deep Grasping Methodology!Learn More