Operators
suggest changeDart has the operators you know from C, Java and JavaScript, plus a few of its own: ~/ for integer division, ?? and ?. for null handling, .. for cascades, ... for spreading collections, and is / as for type tests.
Most operators are methods. a + b calls the + method on a, so your classes can define their own operators.
This article covers:
- arithmetic, including how
/,~/and%differ from other languages - increment, decrement and compound assignment
- equality, relational and type test operators
- logical, conditional and null-aware operators
- cascades and spreads
- bitwise and shift operators
- precedence and common mistakes
- defining operators in your own classes, extensions and extension types
The examples were run with Dart 3.13.
Arithmetic operators
| Operator | Meaning |
|---|---|
+ |
addition |
- |
subtraction |
-expr |
unary minus |
* |
multiplication |
/ |
division, always returns double |
~/ |
truncating division, returns int |
% |
modulo (Euclidean) |
void main() {
print(7 + 2); // 9
print(7 - 2); // 5
print(7 * 2); // 14
print(7 / 2); // 3.5: always a double
print(6 / 2); // 3.0: still a double
print(7 ~/ 2); // 3: truncating integer division
print(7 % 2); // 1
print(-7); // unary minus
print(7.5 ~/ 2); // 3: ~/ on doubles returns an int
print((7 / 2).runtimeType); // double
print((7 ~/ 2).runtimeType); // int
}
/ always produces a double, even for two int operands that divide evenly. If you want an int, use ~/ instead of (a / b).toInt(). It's shorter and avoids the round trip through floating point.
Negative numbers: % vs remainder()
~/ truncates toward zero, like integer division in C or Java. % is different: it's the Euclidean modulo, and its result is never negative. If you want the C/Java/JavaScript behavior, where the result has the sign of the dividend, use remainder():
void main() {
// ~/ truncates toward zero
print(-7 ~/ 2); // -3
// % is Euclidean modulo: the result is never negative
print(-7 % 2); // 1
print(7 % -2); // 1
// remainder() has the sign of the dividend (like % in C, Java, JS)
print((-7).remainder(2)); // -1
// so this always gives a valid index, even for negative i
const days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
var i = -1;
print(days[i % days.length]); // Sun
print(5.5 % 2); // 1.5
}
Dart's % is handy for wrapping indexes in circular buffers. Keep the difference in mind when porting code: -7 % 2 is 1 in Dart, but -1 in Java and JavaScript.
Division by zero
Floating-point division by zero doesn't throw. It produces Infinity or NaN. Integer division (~/) and % by zero throw:
void main() {
print(1 / 0); // Infinity
print(-1 / 0); // -Infinity
print(0 / 0); // NaN
print(0.0 / 0 == 0.0 / 0); // false: NaN is not equal to itself
print((0 / 0).isNaN); // true
try {
print(1 ~/ 0);
} on UnsupportedError catch (e) {
print('~/: $e');
}
try {
print(1 % 0);
} on UnsupportedError catch (e) {
print('%: $e');
}
}
Output:
Infinity
-Infinity
NaN
false
true
~/: IntegerDivisionByZeroException
%: IntegerDivisionByZeroException
Use isNaN to check for NaN, never == double.nan. Native int is 64-bit and wraps around silently on overflow. For bigger numbers see BigInt.
+, * and [] on strings and lists
These operators are also defined on String and List:
void main() {
print('ab' + 'cd'); // abcd
print('-' * 20); // --------------------
print('na' * 4 + ' batman'); // nananana batman
print([1, 2] + [3]); // [1, 2, 3]
print('dart'[0]); // d
}
For building strings, interpolation ('$a$b') is usually preferred over +. See Concatenation and interpolation.
Increment and decrement
++ and -- add or subtract 1. The prefix form (++a) evaluates to the new value. The postfix form (a++) evaluates to the old value:
void main() {
var a = 5;
var b = a++; // b gets the old value, then a is incremented
print('a=$a b=$b'); // a=6 b=5
var c = 5;
var d = ++c; // c is incremented first, d gets the new value
print('c=$c d=$d'); // c=6 d=6
var n = 10;
n--;
--n;
print(n); // 8
// works on anything you can assign to: fields, list elements
final list = [1, 2, 3];
list[0]++;
print(list); // [2, 2, 3]
}
On a Map, ++ doesn't work, because map[key] returns a nullable value:
final counts = <String, int>{'a': 0};
counts['a']++; // error: Operator '+' cannot be called on 'int?' because it is potentially null.
Write out the assignment with ?? or ! instead:
void main() {
final counts = <String, int>{};
for (final w in 'a b a c a'.split(' ')) {
counts[w] = (counts[w] ?? 0) + 1;
}
print(counts); // {a: 3, b: 1, c: 1}
counts['b'] = counts['b']! + 1;
print(counts); // {a: 3, b: 2, c: 1}
}
Assignment operators
= assigns. Every binary arithmetic and bitwise operator also has a compound form, so a op= b means a = a op b. The list is +=, -=, *=, /=, ~/=, %=, &=, |=, ^=, <<=, >>=, >>>= and ??=:
void main() {
var x = 10;
x += 5; // x = x + 5
print(x); // 15
x -= 3;
print(x); // 12
x *= 2;
print(x); // 24
x ~/= 5;
print(x); // 4
x %= 3;
print(x); // 1
x <<= 4;
print(x); // 16
double y = 10;
y /= 4;
print(y); // 2.5
var s = 'ab';
s += 'cd';
s *= 2;
print(s); // abcdabcd
final config = <String, String>{'port': '8080'};
config['host'] ??= 'localhost'; // assigns: key is missing
config['port'] ??= '80'; // no effect: key has a value
print(config); // {port: 8080, host: localhost}
// assignment is an expression; its value is the assigned value
int a, b;
a = b = 7;
print('$a $b'); // 7 7
}
Compound assignment keeps the variable's type. / returns a double, so /= on an int variable doesn't compile:
var x = 10; // inferred as int
x /= 4; // Error: A value of type 'double' can't be assigned to a variable of type 'int'.
Use ~/=, or declare the variable as double (or num).
Equality and relational operators
| Operator | Meaning |
|---|---|
== |
equal |
!= |
not equal |
> < >= <= |
greater, less, greater or equal, less or equal |
void main() {
print(3 == 3.0); // true: int and double compare by value
print('dart' == 'da' + 'rt'); // true: strings compare by content
print([1, 2] == [1, 2]); // false: lists compare by identity
print((1, 'a') == (1, 'a')); // true: records compare by fields
print(null == null); // true
print(2 < 3); // true
print(2.5 >= 2); // true
print(2 != 3); // true
// strings have no < operator; use compareTo
print('apple'.compareTo('banana') < 0); // true
}
a == b calls a.operator ==(b), after handling null: if either side is null, the result is true only if both are. That's why your operator == never receives null. a != b is always !(a == b) and can't be defined separately.
Classes compare by identity unless they override ==. The details, including hashCode and identical(), are in Equality and comparison.
Type test operators
| Operator | Meaning |
|---|---|
is |
true if the object has the type |
is! |
true if the object doesn't have the type |
as |
cast, throws if the object doesn't have the type |
Object parse(String s) => int.tryParse(s) ?? s;
void main() {
Object v = parse('42');
print(v is int); // true
print(v is! String); // true
print(v is num); // true: int is a subtype of num
// `is` promotes the variable inside the guarded block
if (v is int) {
print(v.isEven); // true: v has type int here
}
// `as` casts, and throws if the value has a different type
Object w = parse('hello');
print((w as String).toUpperCase()); // HELLO
try {
print(w as int);
} on TypeError catch (e) {
print(e);
}
Object? nothing;
print(nothing is int); // false: null is not an int
print(nothing is int?); // true
}
Output:
true
true
true
true
HELLO
type 'String' is not a subtype of type 'int' in type cast
false
true
Prefer is with promotion over as. After an is check, the compiler knows the type, and there's no cast that can fail at runtime. For checking several types at once, a switch with type patterns is cleaner than a chain of is checks. See Pattern matching.
Logical operators
| Operator | Meaning |
|---|---|
!expr |
not |
&& |
and |
|| |
or |
&& and || short-circuit: the right side is evaluated only if it can change the result:
bool check(String name, bool result) {
print(' evaluated $name');
return result;
}
String? readName() => null;
void main() {
print('false && ...');
print(check('a', false) && check('b', true));
print('true || ...');
print(check('a', true) || check('b', false));
print(!true); // false
// short-circuiting makes this safe
final s = readName();
if (s != null && s.isNotEmpty) print('non-empty');
print(s == null || s.isEmpty); // true
}
Output:
false && ...
evaluated a
false
true || ...
evaluated a
true
false
true
Dart has no "truthy" values. Operands of !, &&, || and conditions in if and while must be bool. 0, '' and null are not false:
var n = 0;
if (n) print('zero is truthy?'); // Error: A value of type 'int' can't be assigned to a variable of type 'bool'.
Write n != 0, s.isNotEmpty or x != null explicitly.
Conditional and null-aware operators
| Operator | Meaning |
|---|---|
cond ? a : b |
a if cond is true, otherwise b |
a ?? b |
a if it's not null, otherwise b |
a ??= b |
assign b to a only if a is null |
a?.b |
null if a is null, otherwise a.b |
a?[i] |
null if a is null, otherwise a[i] |
a! |
a, or throw if it's null |
String describe(int n) => n.isEven ? 'even' : 'odd';
class User {
final String name;
final String? nickname;
final List<String>? tags;
User(this.name, {this.nickname, this.tags});
}
User? find(String name) => null;
void main() {
print(describe(3)); // odd
final temp = 31;
final label = temp < 0 ? 'freezing' : temp < 25 ? 'mild' : 'hot';
print(label); // hot
final u = User('Alice', tags: ['admin']);
final nobody = find('bob');
print(u.nickname ?? u.name); // Alice
print(nobody?.name); // null
print(nobody?.name.length); // null: the whole chain short-circuits
print(u.tags?[0]); // admin
print(nobody?.tags?[0] ?? 'no tags'); // no tags
print(u.nickname!.length); // throws: nickname is null
}
The last line throws:
Unhandled exception:
Null check operator used on a null value
Note nobody?.name.length: there's no ?. before length, and it's still safe. When nobody is null, the rest of the chain is skipped.
Nested ternaries like label above are fine for two or three cases. For more, use a switch expression. These operators and flow analysis are covered in more depth in Null safety.
Cascades: .. and ?..
A cascade performs a sequence of operations on one object. a..b()..c = 1 calls a.b(), sets a.c = 1, and evaluates to a:
class Request {
String method = 'GET';
String url = '';
final headers = <String, String>{};
String? body;
@override
String toString() => '$method $url $headers ${body ?? ''}';
}
Request? lookup(bool found) => found ? Request() : null;
void main() {
final req = Request()
..method = 'POST'
..url = 'https://example.com/api'
..headers['Content-Type'] = 'application/json'
..headers.addAll({'Accept': 'application/json'})
..body = '{"x":1}';
print(req);
// the value of a cascade is the receiver, not the result of the last call
final sorted = [3, 1, 2]..sort();
print(sorted); // [1, 2, 3]
// without the cascade: sort() returns void
// final bad = [3, 1, 2].sort(); // error: void can't be used
// ?.. starts a null-aware cascade
lookup(false)
?..method = 'DELETE'
..url = '/x';
print(lookup(true)
?..method = 'PUT'
..url = '/y'); // PUT /y {}
// StringBuffer is a common cascade target
final sb = StringBuffer()
..write('a')
..write('b')
..writeln('c');
print(sb.toString().trim()); // abc
}
Output:
POST https://example.com/api {Content-Type: application/json, Accept: application/json} {"x":1}
[1, 2, 3]
PUT /y {}
abc
?.. is only needed on the first section. If the receiver is null, the whole cascade is skipped. Cascades have the lowest precedence of all operators, so a ?? b..c() calls c() on the result of a ?? b.
Spread: ... and ...?
Inside a list, set or map literal, ... inserts all elements of another collection. ...? does the same but skips a null collection:
void main() {
final base = [1, 2];
List<int>? extra;
final isAdmin = true;
final all = [0, ...base, ...?extra, if (isAdmin) 99, for (final n in base) n * 10];
print(all); // [0, 1, 2, 99, 10, 20]
final defaults = {'color': 'red', 'size': 'M'};
final merged = {...defaults, 'size': 'L'};
print(merged); // {color: red, size: L}
}
With maps, later entries override earlier ones, which makes {...defaults, ...overrides} a simple merge. Spreads work only in collection literals. Dart has no spread for function arguments (see Variadic parameters).
Bitwise and shift operators
On int, Dart has & (and), | (or), ^ (xor), ~ (complement), << (shift left), >> (arithmetic shift right) and >>> (logical shift right):
void main() {
const a = 0x0C; // 1100
const b = 0x0A; // 1010
String bin(int n) => n.toRadixString(2).padLeft(4, '0');
print(bin(a & b)); // 1000
print(bin(a | b)); // 1110
print(bin(a ^ b)); // 0110
print(~a); // -13: all 64 bits are flipped
print(1 << 10); // 1024
print(-16 >> 2); // -4: arithmetic shift keeps the sign
print(-16 >>> 60); // 15: logical shift fills with zeros
// bool also has &, | and ^, which do NOT short-circuit
print(true ^ true); // false
}
On the web, int is a JavaScript number and bitwise operations are limited to 32 bits. Bit manipulation covers masks, flags and these web differences in depth.
Precedence
From highest to lowest:
| Description | Operators |
|---|---|
| unary postfix | expr++ expr-- () [] ?[] . ?. ! |
| unary prefix | -expr !expr ~expr ++expr --expr await expr |
| multiplicative | * / % ~/ |
| additive | + - |
| shift | << >> >>> |
| bitwise AND | & |
| bitwise XOR | ^ |
| bitwise OR | | |
| relational and type test | >= > <= < as is is! |
| equality | == != |
| logical AND | && |
| logical OR | || |
| if-null | ?? |
| conditional | expr1 ? expr2 : expr3 |
| cascade | .. ?.. |
| assignment | = *= /= += -= &= ^= etc. |
| spread | ... ...? |
A few results that surprise people:
int? lookup(String key) => {'a': 5}[key];
void main() {
// unary minus binds looser than method calls
print(-2.abs()); // -2: parsed as -(2.abs())
print((-2).abs()); // 2
// ?? has lower precedence than arithmetic
print(lookup('a') ?? 0 + 10); // 5: parsed as lookup('a') ?? (0 + 10)
print((lookup('a') ?? 0) + 10); // 15
print((lookup('z') ?? 0) + 10); // 10
// == binds tighter than &&, || and ??
final x = 6;
print(x % 2 == 0 && x > 5); // true
// & binds tighter than ==, unlike in C
print(x & 1 == 0); // true: (x & 1) == 0
// string interpolation needs braces for expressions
print('$x + 1 = ${x + 1}'); // 6 + 1 = 7
}
The ?? case is the most common bug: count ?? 0 + 1 doesn't add 1 when count is not null. When mixing ?? with other operators, add parentheses.
Defining operators in your classes
You define an operator with the operator keyword. These operators can be defined:
< > <= >= == ~
- + / ~/ * %
| ^ & << >>> >>
[]= [] unary-
You can't define !=, &&, ||, !, ??, ?., .., is, as, =, ++, or the compound assignments. != is derived from ==, ++ and += are derived from +, and so on. For example, this doesn't compile:
class A {
bool operator !=(Object other) => false; // Error: The string '!=' isn't a user-definable operator.
}
A 2D vector with arithmetic, unary minus, indexing and value equality:
class Vec {
final double x, y;
const Vec(this.x, this.y);
Vec operator +(Vec other) => Vec(x + other.x, y + other.y);
Vec operator -(Vec other) => Vec(x - other.x, y - other.y);
Vec operator *(double factor) => Vec(x * factor, y * factor);
Vec operator -() => Vec(-x, -y); // unary minus
double operator [](int i) => switch (i) {
0 => x,
1 => y,
_ => throw RangeError.index(i, this, 'index', null, 2),
};
@override
bool operator ==(Object other) => other is Vec && other.x == x && other.y == y;
@override
int get hashCode => Object.hash(x, y);
@override
String toString() => 'Vec($x, $y)';
}
void main() {
const a = Vec(1, 2);
const b = Vec(3, 4);
print(a + b); // Vec(4.0, 6.0)
print(b - a); // Vec(2.0, 2.0)
print(a * 3); // Vec(3.0, 6.0)
print(-a); // Vec(-1.0, -2.0)
print(a[1]); // 2.0
print(a + b == const Vec(4, 6)); // true
print(a != b); // true: != is !(a == b)
// compound assignment uses the operator automatically
var p = a;
p += b;
p *= 2;
print(p); // Vec(8.0, 12.0)
}
Unary minus is operator -() with no parameters. Binary minus is operator -(other) with one. Operators are always called on the left operand, so a * 3 works, but 3 * a doesn't: that would call int.*, which doesn't accept a Vec.
When you override ==, always override hashCode too, otherwise your objects behave incorrectly in sets and as map keys.
Index assignment and callable objects
operator []= makes obj[key] = value work. It takes two parameters and should return void. A method named call isn't an operator, but it makes instances callable like functions:
class Grid {
final int width, height;
final List<String> _cells;
Grid(this.width, this.height) : _cells = List.filled(width * height, '.');
String operator [](({int x, int y}) p) => _cells[p.y * width + p.x];
void operator []=(({int x, int y}) p, String v) => _cells[p.y * width + p.x] = v;
@override
String toString() => [
for (var r = 0; r < height; r++) _cells.sublist(r * width, (r + 1) * width).join(),
].join('\n');
}
class Multiplier {
final int factor;
const Multiplier(this.factor);
int call(int n) => n * factor; // makes instances callable like functions
}
void main() {
final g = Grid(4, 2);
g[(x: 1, y: 0)] = '#';
g[(x: 3, y: 1)] = '@';
print(g[(x: 1, y: 0)]); // #
print(g);
const triple = Multiplier(3);
print(triple(7)); // 21
print([1, 2, 3].map(triple.call).toList()); // [3, 6, 9]
}
Output:
#
.#..
...@
21
[3, 6, 9]
The index can be any type. Here a record (x: 1, y: 0) gives a two-dimensional index.
Operators in extensions and extension types
You can add operators to types you don't own with extension methods. Extension types can define operators too, which gives you a zero-cost wrapper with its own arithmetic:
extension DateTimeOps on DateTime {
DateTime operator +(Duration d) => add(d);
Duration operator -(DateTime other) => difference(other);
bool operator <(DateTime other) => isBefore(other);
}
extension StringMinus on String {
String operator -(String other) => replaceAll(other, '');
}
extension type Money(int cents) {
Money operator +(Money o) => Money(cents + o.cents);
bool operator <(Money o) => cents < o.cents;
String get display => '\$${(cents / 100).toStringAsFixed(2)}';
}
void main() {
final start = DateTime.utc(2026, 10, 17, 9);
final end = start + const Duration(hours: 2, minutes: 30);
print(end); // 2026-10-17 11:30:00.000Z
print(end - start); // 2:30:00.000000
print(start < end); // true
print('banana' - 'an'); // ba
final total = Money(1999) + Money(501);
print(total.display); // $25.00
print(Money(100) < total); // true
}
Extensions can't define ==. Every object already has == from Object, and an instance member always wins over an extension member.
Use custom operators only where the meaning is obvious, as in math types (vectors, matrices, money, durations). 'banana' - 'an' is short, but a reader has to look it up. A method named removeAll would be clearer.