Thuta Learning
Dart
BasicProgrammingBeginner

Operators

DartLesson 835 min

What you'll walk away with

  • Use the arithmetic operators and predict the results of /, ~/ and %, negative numbers included
  • Combine comparison and logical operators while understanding short-circuiting and precedence
  • Explain when to use ??, ??=, ?. and !, and what risk ! carries
  • Use the cascade (..) and the type-test operators is and as

Explain it simply

Explain it simply

Operators are the small symbols that tell Dart what to do with values: add them, compare them, combine yes/no answers. Think of the keys on a calculator, plus a few extra keys built for the situation where a value might be missing.

Every operator takes operands and produces a result of a specific type: / gives a double, and comparisons give a bool. Once you know the result type, you can predict what a line does before running it.

Problem → Why → Solution

The problem: familiar symbols, different behaviour

People arriving from other languages meet two surprises in Dart's operators. The first is the weekday wrap-around (today - 3) % 7. In JavaScript, Java and C, with today equal to 1 this gives -2, and indexing with a negative day number then fails. In Dart the remainder is never negative, so it gives 5. The second is using nickname.length directly when the user never set a nickname; Dart refuses to compile that.

surprises.dart
void main() {
  int today = 1;                       // Monday
  int threeDaysAgo = (today - 3) % 7;  // -2 in many languages, but in Dart?
  print(threeDaysAgo);

  String? nickname;                    // the user never set one
  print(nickname.length);              // error: nickname may be null
  int half = 10 / 4;                   // error: / produces a double
}

Why symbols cannot be trusted across languages

Symbols such as % are defined by different rules in different languages, so carrying habits across is not enough. Knowing Dart's exact rules (-7 % 3 is 2, while (-7).remainder(3) is -1) prevents bugs before they appear. The null-aware operators also turn a possibly-missing value into a compile-time problem and put the fix (?? or ?.) in your hands.

Core concept: operator families and their result types

The arithmetic operators are + - * / ~/ %. / always returns a double, and ~/ truncates toward zero, so -7 ~/ 2 is -3. % is Euclidean modulo, so its result is never negative: -7 % 3 is 2. (-7).remainder(3) follows the sign of the left operand and gives -1. Dividing an int by zero with ~/ or % (1 ~/ 0, 1 % 0) throws an IntegerDivisionByZeroException, while 1 / 0 evaluates to Infinity. + also joins Strings and * repeats a string ('ab' * 3 is 'ababab'), but 'a' + 1 is a compile error.

The comparison operators (== != > < >= <=) return a bool. == compares by value for numbers and strings, so 1 == 1.0 is true, but two lists with the same elements are not == because lists compare by identity. You cannot chain 1 < a < 10; write (1 < a) && (a < 10). A condition must be a bool, so an int such as if (count) is not accepted.

The logical operators && || ! short-circuit: if the left side of && is false, the right side is never evaluated, and the same holds when the left side of || is true. That is why stock > 0 && 100 ~/ stock > 5 cannot divide by zero when stock is 0. By precedence, ! binds tighter than && and && binds tighter than ||, so true || false && false is true. The ternary cond ? a : b is a compact if/else.

Assignment has = plus += -= *= ~/=, and ++ and -- work in prefix and postfix form: i++ returns the old value and then increments, while ++i increments first. The null-aware operators are ?? (use the right side when the left is null), ??= (assign only when the variable is null), ?. (give null instead of an error when the target is null) and ! (you vouch that it is not null). If you use ! and the value really is null, the program crashes at run time with "Null check operator used on a null value".

The last family deals with objects and types. is tests a type, is! tests that it is not that type, and as casts; a wrong as throws something like "type 'String' is not a subtype of type 'int' in type cast". The cascade (..) performs several operations on the same object in a row and evaluates to that object itself.

Mental model: keys on a calculator
  1. Operands go in
  2. Their types pick the rule
  3. The result type is fixed
  4. Precedence decides the order

When in doubt, add parentheses; they cost nothing and spare readers from memorising precedence.

General pattern

dart
result = left + right;           // arithmetic: + - * / ~/ %
flag = left >= right && ready;   // compare first, then combine
value = maybeNull ?? fallback;   // fallback when the left side is null
maybeNull ??= fallback;          // assign only while it is null
length = maybeNull?.length;      // null instead of an error
object..first()..second();       // cascade: many calls, one object

The first two lines are numeric and logical calculations. The last four are the null-aware operators and the cascade, each handling one special situation briefly and clearly.

Example: price checks, remainders and an optional coupon

This example subtracts a discount from a price and uses && to decide whether the purchase is allowed. Then it tries % and ~/ on a negative number. The last part deals with a coupon that may or may not exist, using ?? and ??=.

operators.dart
void main() {
  int price = 12000;
  int discount = 2000;
  int finalPrice = price - discount;

  bool hasEnoughMoney = finalPrice <= 10000;
  bool isMember = true;

  print('Final price: $finalPrice');

  if (hasEnoughMoney && isMember) {
    print('You can buy this item with member benefit.');
  }

  print(7 % 2);     // remainder
  print(-7 % 3);    // % is never negative here
  print(-7 ~/ 2);   // truncates toward zero

  String? coupon;
  String label = coupon ?? 'no coupon';
  coupon ??= 'WELCOME';
  print(label);
  print(coupon?.length);
}

Code breakdown

  1. Line 4int finalPrice = price - discount;

    Subtracting two ints gives an int: 12000 - 2000 is 10000.

  2. Line 6bool hasEnoughMoney = finalPrice <= 10000;

    <= compares and yields a bool. 10000 <= 10000 holds, so the result is true.

  3. Line 11if (hasEnoughMoney && isMember) {

    && is true only when both sides are true; if the left side is false the right side is not even evaluated.

  4. Line 16print(-7 % 3);

    % is Euclidean modulo, so even with a negative left side the result is 2. In C or Java the same expression gives -1.

  5. Line 17print(-7 ~/ 2);

    -3.5 is truncated toward zero, giving -3, not -4: this is truncation, not floor.

  6. Line 20String label = coupon ?? 'no coupon';

    coupon is null, so ?? supplies its right-hand value 'no coupon' for label.

  7. Line 21coupon ??= 'WELCOME';

    coupon is null, so 'WELCOME' is assigned here. Writing it again later would change nothing, because coupon is no longer null.

You should see
Final price: 10000
You can buy this item with member benefit.
1
2
-3
no coupon
7

Precedence and short-circuiting

Order (high to low)OperatorsExample
1. Unary!x -x x++ ++x!ready
2. Multiplicative* / ~/ %2 + 3 * 4 is 14
3. Additive+ -a - b - c runs left to right
4. Relational< > <= >= is asage >= 18
5. Equality== !=name == 'Aye'
6-7. Logical&& first, then ||a || b && c
8-10. Lowest??, then ? :, then =x = a ?? b

The code below shows why the results come out as they do under precedence, and why a function is sometimes not called under short-circuiting. When isReady() sits on the right of false && ... and true || ..., the text "checked" never appears; only the final true && isReady() prints it. Be careful about putting a function with side effects on the right-hand side.

precedence.dart
bool isReady() {
  print('checked');
  return true;
}

void main() {
  print(2 + 3 * 4);               // 14
  print((2 + 3) * 4);             // 20
  print(true || false && false);  // true: && binds tighter than ||

  int stock = 0;
  if (stock > 0 && 100 ~/ stock > 5) {
    print('plenty');
  } else {
    print('out of stock');        // the division was never attempted
  }

  print(false && isReady());      // isReady() is not called
  print(true || isReady());       // isReady() is not called
  print(true && isReady());       // prints checked, then true
}

Null-aware operators and the cascade

?. skips the rest of the chain and gives null as soon as it meets a null, so in nickname?.toUpperCase().length neither toUpperCase nor length runs when nickname is null. Combine it with ?? as in nickname?.length ?? 0 to supply a fixed value for the null case. The cascade helps when you call several methods on one object such as a StringBuffer or a list, saving you from repeating the variable name. The value of the whole cascade is the first object itself, not the results of the methods in between.

null_aware.dart
void main() {
  String? nickname;
  print(nickname ?? 'guest');
  print(nickname?.length);

  nickname ??= 'Aye';
  nickname ??= 'Ko';              // already set, so this line does nothing
  print(nickname);

  final buffer = StringBuffer()
    ..write('Total: ')
    ..write(1200)
    ..write(' MMK');
  print(buffer);

  final tags = <String>['a']..add('b')..addAll(['c', 'd']);
  print(tags);
}

Treat ! as a last resort

name! tells the compiler 'this is not null, I promise'. If the promise is wrong the compiler can no longer help and the program crashes at run time. Supplying a fallback with ??, checking with if (name != null), or using ?. is safer.

In real projects

Where this shows up in real projects

In Flutter, Text(user?.name ?? 'Guest') is one of the most common lines you will see, and index % 2 == 0 is used to alternate row colours in a list. Pagination computes the number of pages with (total + perPage - 1) ~/ perPage, and splitting seconds into minutes and seconds uses ~/ 60 and % 60. Lazy loading a cached value exactly once, as in _cache ??= loadData(), is also everywhere.

Backends and command-line tools rely on short-circuiting in guard conditions: items.isNotEmpty && items.first > 0 cannot crash on an empty list. When reading JSON, code often separates cases with a type test such as value is int before using the value. When building configuration objects, a cascade keeps the sequence of settings tidy. Reviewers look closely at ! and as in code review because those two operators are the ones that can crash at run time.

Common mistakes

Common mistakes

1. Chaining comparisons

Writing 1 < a < 10 gives "A comparison expression can't be an operand of another comparison expression." The first comparison would produce a bool that is then compared with 10, which makes no sense. Split it into 1 < a && a < 10.

2. Writing = where == is meant

if (count = 3) is reported as "A value of type 'int' can't be assigned to a variable of type 'bool'." because the assignment yields an int while a condition needs a bool. The compiler catches it, and when you see = in that message the fix is to write ==.

3. Silencing null with ! instead of handling it

Running String? s; print(s!.length); stops with "Null check operator used on a null value". The ! does not remove the problem, it moves it from compile time to run time. Replace it with ?. and ??, or an explicit null check.

4. Overlooking division by zero

With ints, 1 ~/ 0 and 1 % 0 throw an IntegerDivisionByZeroException, but 1 / 0 gives Infinity and 0.0 / 0.0 gives NaN without any error. Check the divisor before integer division, and test double results with isNaN or isInfinite before showing them.

Best practices

Best practices

  • Add parentheses when you mix && and ||; code that reads clearly beats code that relies on remembered precedence.
  • For a possibly-null value, prefer x ?? 'a' over a ternary such as x == null ? 'a' : x.
  • Use ! and as only when you are certain; an is check that gives type promotion is usually safer.
  • Do not hide a function with side effects on the right of && or ||; short-circuiting may skip it.

Mini challenge

Mini challenge: time, weekdays and names

Apply three groups of operators: splitting seconds into minutes, wrapping around the week, and handling a missing nickname.

  • String formatDuration(int totalSeconds): use ~/ and % to return text like '62 min 5 sec'
  • int weekdayAfter(int today, int offset): return a day number from 0 to 6, and work even when offset is negative
  • String greetingFor(String? nickname): 'Hello, AYE!' in capitals when a nickname exists, otherwise 'Hello, guest!'
  • In main, print formatDuration(3725), weekdayAfter(1, -3), weekdayAfter(5, 4), greetingFor(null) and greetingFor('Aye')
helpers.dart
String formatDuration(int totalSeconds) {
  // TODO: split into whole minutes and leftover seconds
}

int weekdayAfter(int today, int offset) {
  // TODO: wrap into 0..6, even for negative offsets
}

String greetingFor(String? nickname) {
  // TODO: uppercase the nickname when present, otherwise use 'guest'
}

void main() {
  // TODO: print the five requested calls
}

Expected: 62 min 5 sec 5 2 Hello, guest! Hello, AYE!

Show hint

Divide 3725 seconds by 60 with ~/ for minutes and take % 60 for the leftover seconds. For negative offsets, rely on Dart's % never being negative. For the nickname, combine ?. with ??.

Show solution
helpers.dart
String formatDuration(int totalSeconds) {
  final minutes = totalSeconds ~/ 60;
  final seconds = totalSeconds % 60;
  return '$minutes min $seconds sec';
}

int weekdayAfter(int today, int offset) => (today + offset) % 7;

String greetingFor(String? nickname) {
  return 'Hello, ${nickname?.toUpperCase() ?? 'guest'}!';
}

void main() {
  print(formatDuration(3725));
  print(weekdayAfter(1, -3));
  print(weekdayAfter(5, 4));
  print(greetingFor(null));
  print(greetingFor('Aye'));
}

Quick quiz 1 / 3

What does print(-7 % 3); output?

Quick quiz 2 / 3

What does String? name; name ??= 'Aye'; name ??= 'Ko'; print(name); print?

Quick quiz 3 / 3

What does print(7 ~/ 2 + 7 % 2); output?

What to remember

  • / returns a double, ~/ returns an int truncated toward zero, and % is never negative in Dart; only (-7).remainder(3) keeps the sign.
  • && and || short-circuit, ! binds tighter than && and && tighter than ||; add parentheses when unsure.
  • ?? supplies a fallback, ??= assigns only while null, ?. stops the chain at null, and ! can crash at run time.
  • The cascade (..) performs several calls on one object and evaluates to that object.

Dart language overview — Dart

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Operators | Thuta Learning