Operators in Dart are special symbols or keywords that perform operations on operands. They are essential for manipulating data and controlling program flow. Understanding Dart operators is crucial for writing efficient and expressive code.
Arithmetic operators perform mathematical calculations on numeric values.
+
(Addition)-
(Subtraction)*
(Multiplication)/
(Division)~/
(Integer Division)%
(Modulus)Comparison operators compare two values and return a boolean result.
==
(Equal to)!=
(Not equal to)>
(Greater than)<
(Less than)>=
(Greater than or equal to)<=
(Less than or equal to)Logical operators perform boolean logic operations.
&&
(AND)||
(OR)!
(NOT)Assignment operators assign values to variables.
=
(Simple assignment)+=
, -=
, *=
, /=
, %=
(Compound assignment)
void main() {
int a = 10;
int b = 5;
print(a + b); // Output: 15
print(a - b); // Output: 5
print(a * b); // Output: 50
print(a / b); // Output: 2.0
print(a ~/ b); // Output: 2
print(a % b); // Output: 0
a += 3; // Equivalent to: a = a + 3
print(a); // Output: 13
}
void main() {
int x = 5;
int y = 10;
print(x == y); // Output: false
print(x != y); // Output: true
print(x < y); // Output: true
print(x > y); // Output: false
bool isTrue = true;
bool isFalse = false;
print(isTrue && isFalse); // Output: false
print(isTrue || isFalse); // Output: true
print(!isTrue); // Output: false
}
Dart follows a specific order of precedence for operators. Understanding this order is crucial for writing correct expressions. Here's a simplified precedence table, from highest to lowest:
expr++
, expr--
)-expr
, !expr
)*
, /
, %
, ~/
)+
, -
)>=
, >
, <=
, <
, as
, is
, is!
)==
, !=
)&&
)||
)?:
)=
, *=
, /=
, etc.)??
, ?..
, ?.
) to handle nullable values safely.Mastering Dart operators is essential for writing efficient and expressive code. They form the foundation for more complex operations and are crucial in control flow statements and functions. Practice using these operators in various scenarios to become proficient in Dart programming.