Dart Operators
Dart Operators
Operators are symbols that do something with values and variables.
In the example below, we use the + operator to add two numbers:
Result:
150
The values on each side of an operator are called operands.
The operands can be values, variables, or a mix of both:
Example
void main() {
int sum1 = 100 + 50;
int sum2 = sum1 + 250;
int sum3 = sum2 + sum2;
print(sum1);
print(sum2);
print(sum3);
}
Try it Yourself »
Result:
150
400
800
Operator Groups
The Dart operators can be divided into these groups:
| Group | Operators | Used for |
|---|---|---|
| Arithmetic operators | + - * / ~/ % ++ -- | Math with numbers |
| Assignment operators | = += -= *= /= ~/= %= ??= | Giving values to variables |
| Comparison operators | == != > < >= <= | Comparing two values |
| Logical operators | && || ! | Combining true and false values |
| Type test operators | is is! as | Checking and changing the type of a value |
| Null-aware operators | ?? ??= ?. ?.. ?[] | Working with values that can be null |
| Cascade notation | .. ?.. | Doing many things with the same object |
Each group has its own chapter.
Click a group name in the table to read more.
Operator Precedence
Operator precedence is the order in which Dart calculates the operators in an expression.
Like in math, multiplication is done before addition:
Result:
14
Dart calculates 3 * 4 first, and then adds 2.
Use parentheses () to calculate a part first:
Result:
20
Tip: Parentheses also make your code easier to read, even when they are not needed.
Operators and Types
What an operator does depends on the type of the values.
With strings, + joins two strings, and * repeats a string:
Example
void main() {
String firstName = 'John';
String lastName = 'Doe';
print(firstName + ' ' + lastName);
print('Ha' * 3);
}
Try it Yourself »
Result:
John Doe
HaHaHa
Comparison operators always give a bool value, true or false:
Result:
true