Overview
Assignment operators are used to assign values to variables. Dart provides compound assignment operators that combine arithmetic operations with assignment, making your code more concise.
Assignment Operators Table
| Operator | Description | Example | Equivalent To |
|---|
= | Simple assignment | x = 5 | - |
+= | Add and assign | x += 5 | x = x + 5 |
-= | Subtract and assign | x -= 3 | x = x - 3 |
*= | Multiply and assign | x *= 2 | x = x * 2 |
/= | Divide and assign | x /= 4 | x = x / 4 |
~/= | Integer divide and assign | x ~/= 4 | x = x ~/ 4 |
%= | Modulo and assign | x %= 3 | x = x % 3 |
Basic Example
Here’s a complete example showing how assignment operators work:
void main() {
//Operadores de Asignación
int numero = 17;
print(numero);
numero += 5; // numero = numero + 5 → numero = 15
print(numero);
numero -= 3; // numero = numero - 3 → numero = 12
print(numero);
numero *= 2; // numero = numero * 2 → numero = 24
print(numero);
numero ~/= 4; // numero = numero ~/ 4 → numero = 6
print(numero);
}
Output:
The comment in the original code has calculation errors, but the actual execution follows the correct logic: 17 + 5 = 22, 22 - 3 = 19, 19 * 2 = 38, 38 ~/ 4 = 9.
Why Use Compound Operators?
Compound assignment operators make your code:
- More concise: Less typing required
- More readable: Clear intent to modify a variable
- Less error-prone: You don’t repeat the variable name
Comparison
// Without compound operator
int counter = 10;
counter = counter + 1; // Longer, repetitive
// With compound operator
int counter = 10;
counter += 1; // Shorter, clearer
For incrementing or decrementing by 1, Dart also provides ++ and -- operators:
counter++ is equivalent to counter += 1
counter-- is equivalent to counter -= 1
Practical Examples
Accumulating Values
int total = 0;
total += 10; // Add 10 to total
total += 20; // Add 20 more
total += 5; // Add 5 more
print(total); // Output: 35
Updating Calculations
double price = 100.0;
price *= 1.15; // Apply 15% tax
price -= 10.0; // Apply $10 discount
print(price); // Output: 105.0
Integer Division Assignment
int items = 50;
items ~/= 3; // Divide into groups of 3
print(items); // Output: 16 (complete groups)