Lesson 8 min
Assignment Operators
00:00 / 00:00
Assignment Operators
Assignment operators are used to assign values to variables. Dart supports a variety of compound assignment operators that perform an operation and assign the result in a single step.
List of Assignment Operators
| Operator | Description | Equivalent Expression |
|---|---|---|
= | Simple assignment | x = y |
+= | Add and assign | x = x + y |
-= | Subtract and assign | x = x - y |
*= | Multiply and assign | x = x * y |
/= | Divide and assign | x = x / y |
~/= | Integer divide and assign | x = x ~/ y |
%= | Modulo and assign | x = x % y |
??= | Null-aware assignment | x = x ?? y (Assigns only if x is null) |
Code Examples
Compound Assignments
dartvoid main() { double price = 100.0; price += 10; // Equivalent to: price = price + 10; print(price); // 110.0 price *= 0.9; // Apply 10% discount print(price); // 99.0 }
Null-Aware Assignment (??=)
The ??= operator assigns a value to a variable only if the variable is currently null.
dartvoid main() { String? username; username ??= "Guest"; print(username); // Guest username ??= "Admin"; // Will not overwrite since username is not null print(username); // Guest }
Summary
- Compound assignment operators make code cleaner and more readable.
- The
??=operator is extremely useful for setting default fallback values for nullable variables.