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

OperatorDescriptionEquivalent Expression
=Simple assignmentx = y
+=Add and assignx = x + y
-=Subtract and assignx = x - y
*=Multiply and assignx = x * y
/=Divide and assignx = x / y
~/=Integer divide and assignx = x ~/ y
%=Modulo and assignx = x % y
??=Null-aware assignmentx = x ?? y (Assigns only if x is null)

Code Examples

Compound Assignments

dart
void 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.

dart
void 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.
WhatsApp