Operators
Prerequisites: Booleans and comparisons
An operator is a symbol that works on values, like + or &&.
Arithmetic and assignment
void main() {
var score = 10;
score += 5;
score -= 2;
score *= 2;
score++;
score ~/= 3;
print(score);
}
9
Logical operators
void main() {
final age = 20;
final hasTicket = true;
print(age >= 18 && hasTicket);
print(age < 13 || age > 65);
print(!hasTicket);
}
true
false
false
&&(and) — true only if both sides are true.||(or) — true if either side is true.!(not) — flipstrueandfalse.
The conditional operator
condition ? valueIfTrue : valueIfFalse picks one of two values:
void main() {
final temperature = 30;
final advice = temperature > 25 ? 'Wear a hat' : 'Bring a jacket';
print(advice);
}
Wear a hat
Type test operators
is checks a value's type; as casts it:
void main() {
Object value = 'hello';
print(value is String);
print(value is int);
}
true
false
Cascade operator: ..
.. calls several methods on the same object, in sequence:
void main() {
final buffer = StringBuffer()
..write('Dart')
..write(' ')
..write('rocks');
print(buffer);
}
Dart rocks
Cascades are very common in Flutter and when configuring objects.
Practice
A shop gives free delivery if an order is over 50 or the customer is a
member. With total = 42 and isMember = true, print Free delivery or
Delivery: 5 EUR using the conditional operator.
Show solution
void main() {
const total = 42;
const isMember = true;
print(total > 50 || isMember ? 'Free delivery' : 'Delivery: 5 EUR');
}
Free delivery