Introduction
Assignment operators assign values to variables. Dart provides a basic assignment operator (=) as well as compound operators that combine arithmetic with assignment, making code shorter and more readable.
Why It Matters
Compound assignment operators reduce repetitive code. Instead of writing x = x + 5, you can write x += 5. This makes your code cleaner and less error-prone.
Basic Assignment
int x = 10; // assigns 10 to x
String name = 'Dart';
bool isReady = true;
Compound Assignment Operators
| Operator | Equivalent To | Example (x=10) | Result |
+= | x = x + n | x += 5 | 15 |
-= | x = x - n | x -= 3 | 7 |
*= | x = x * n | x *= 2 | 20 |
/= | x = x / n | x /= 4 | 2.5 |
~/= | x = x ~/ n | x ~/= 3 | 3 |
%= | x = x % n | x %= 3 | 1 |
??= | assign if null | y ??= 5 | 5 (if y is null) |
Code Example
void main() {
int score = 100;
score += 10;
print(score); // 110
score -= 20;
print(score); // 90
score *= 2;
print(score); // 180
score ~/= 3;
print(score); // 60
score %= 7;
print(score); // 4 (60 % 7 = 4)
// Null-aware assignment
int? bonus;
bonus ??= 50;
print(bonus); // 50 (was null, so assigned)
bonus ??= 100;
print(bonus); // 50 (already has value, no change)
}
Output:
110
90
180
60
4
50
50
Explanation
+= adds a value to the variable and stores the result back.
-= subtracts a value from the variable.
*= multiplies the variable by a value.
~/= performs integer division and updates the variable.
%= finds the remainder and stores it.
??= only assigns if the variable is currently null — very useful for default values.
Notes
- All compound operators are shorthand — they read and write the same variable.
- The
??= operator is unique to Dart and works with nullable types.
- Using
/= on an int variable will cause a compile error since the result is a double. Declare it as double or use ~/=.
Common Mistakes
- Confusing
= (assignment) with == (equality comparison).
- Using
/= with an int variable — the result is a double, causing a type error.
- Expecting
??= to reassign a variable that already has a non-null value.
💪 Exercise
- Start with
int points = 50. Add 25, then multiply by 2, then subtract 30. Print the final value.
- Declare a nullable
String? username. Use ??= to assign a default name if it is null.
- Rewrite
x = x * 3 + 5 using compound operators (hint: two separate statements).
🧠 Quiz
1. What does x ??= 10 do if x is NOT null?
- A) Sets x to 10
- B) Does nothing ✅
- C) Throws an error
- D) Sets x to null
2. Which compound operator performs integer division?
- A) /=
- B) //=
- C) ~/= ✅
- D) div=
Summary
Assignment operators in Dart assign values to variables. Compound operators like +=, -=, *=, ~/=, and %= combine arithmetic with assignment in a single step. The special ??= operator assigns a value only when the variable is null, making it ideal for setting defaults in null-safe code.