Skip to main content
The += operator is a compound assignment operator that performs addition (for numbers) or concatenation (for strings) using the right operand, and assigns the result to the left operand. It serves as syntactic sugar for applying the + operator and the = operator in a single statement.

Syntax

variable += expression;

Operational Semantics

The expression a += b is semantically equivalent to a = a + b, with the distinction that the left-hand operand (a) is evaluated only once. The execution flow is as follows:
  1. Evaluation: The current value of variable is retrieved.
  2. Operation: The + operator is invoked on variable with expression as the argument.
  3. Assignment: The result of the operation is assigned back to variable.

Type Compatibility

The behavior of += depends on the static type of the left-hand operand:
  • Numeric Types (int, double): Performs arithmetic addition.
  • String Type (String): Performs string concatenation.
  • Custom Types: Invokes the user-defined operator + method on the class.

Operator Overloading

Dart does not permit the explicit overloading of the += operator. Instead, the behavior of += is derived implicitly from the implementation of the + operator. To enable += for a custom class, you must define operator +.

Examples

Numeric Addition
int x = 10;
x += 5; // Equivalent to: x = x + 5
// x is now 15
String Concatenation
String text = "Hello";
text += " World"; // Equivalent to: text = text + " World"
// text is now "Hello World"
Evaluation Order (Side Effects) In the following example, the index getter i is evaluated only once, ensuring the index does not increment twice.
List<int> numbers = [10, 20];
int i = 0;

// numbers[0] = numbers[0] + 5
// i is incremented to 1 only once
numbers[i++] += 5; 

print(numbers); // [15, 20]
print(i);       // 1
Master Dart with Deep Grasping Methodology!Learn More