Dart Assignment Operators
Dart Assignment Operators
Assignment operators are used to give values to variables.
The most common one is =, which gives the value on the right to the variable on the left:
Result:
10
25
Compound Assignment
A compound assignment operator does a calculation and an assignment in one step.
x += 5 is a short way to write x = x + 5:
Result:
15
A list of all assignment operators:
| Operator | Example | Same as |
|---|---|---|
= | x = 5 | x = 5 |
+= | x += 3 | x = x + 3 |
-= | x -= 3 | x = x - 3 |
*= | x *= 3 | x = x * 3 |
/= | x /= 3 | x = x / 3 |
~/= | x ~/= 3 | x = x ~/ 3 |
%= | x %= 3 | x = x % 3 |
??= | x ??= 3 | x = x ?? 3 |
Example
void main() {
int x = 20;
x -= 4;
print(x);
x *= 2;
print(x);
x ~/= 5;
print(x);
x %= 4;
print(x);
}
Try it Yourself »
Result:
16
32
6
2
Assignment with Strings
The += operator also works with strings.
It adds text to the end of a string:
Example
void main() {
String greeting = 'Hello';
greeting += ' World';
print(greeting);
}
Try it Yourself »
Result:
Hello World
The /= Operator and int
The / operator always gives a double.
So you cannot use /= on an int variable:
Result:
main.dart:3:9: Error: A value of type 'double' can't be assigned to a variable of type 'int'.
total /= 2;
^
Use a double variable with /=, or use ~/= for integer division:
Example
void main() {
double price = 10;
price /= 4;
print(price);
int total = 10;
total ~/= 4;
print(total);
}
Try it Yourself »
Result:
2.5
2
The ??= Operator
The ??= operator gives a value to a variable only if the variable is null:
Example
String? color;
void main() {
color ??= 'blue';
print(color);
color ??= 'red';
print(color);
}
Try it Yourself »
Result:
blue
blue
The second ??= does not change color, because it already has a value.
You can read more in the Null-aware Operators chapter.