Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 61 ยท Types and Operators

Booleans and Operators

Learn Dart's bool type and its operators: arithmetic, ~/ and %, comparison, logical short-circuiting, bitwise, cascade (..), and the is, is! and as operators.

Every program makes decisions and calculates things, and operators are the small symbols that do both. Dart has the familiar ones from C, Java and JavaScript, plus a few of its own: integer division with ~/, the cascade operator .., and the type test operators is, is! and as. Before them comes the humble bool, the type that every decision rests on.

This lesson tours all of these. Real Dart is shown in read-only blocks. Where the same idea can be demonstrated with TypeScript, a runnable stand-in follows, and its differences from Dart are called out.

The bool type

A bool has exactly two values, true and false. Unlike JavaScript or Python, Dart has no truthiness: conditions must be real booleans. A number, a string or a list is never silently converted.

DART
void main() {
  bool isOpen = true;
  var hasTickets = false;

  if (isOpen && !hasTickets) {
    print('Open but sold out');
  }

  int count = 3;
  // if (count) { ... }      // error: 'int' can't be used as a condition
  if (count > 0) {            // write the comparison out
    print('There are $count items');
  }
}
TEXT
Open but sold out
There are 3 items

This rule removes a whole class of bugs, such as treating 0 or an empty string as "false" by accident. If you want to test for emptiness, say so: name.isEmpty, list.isNotEmpty, count != 0.

Arithmetic operators

The arithmetic operators work on int, double and num (see Numbers: int and double):

Operator Meaning Example Result
+ - * add, subtract, multiply 7 * 3 21
/ divide, always gives a double 7 / 2 3.5
~/ integer (truncating) division 7 ~/ 2 3
% modulo (never negative for a positive divisor) -7 % 3 2
-x negate -(5) -5

Two of these surprise newcomers. First, / returns a double even when both operands are int, so 8 / 2 is 4.0. Use ~/ when you want a whole-number result. Second, % is a true modulo: with a positive divisor the result is between 0 and the divisor, even for negative left operands. If you need the sign-preserving remainder known from C or Java, call (-7).remainder(3), which is -1.

DART
void main() {
  print(7 / 2);          // 3.5
  print(8 / 2);          // 4.0
  print(7 ~/ 2);         // 3
  print(-7 ~/ 2);        // -3   (truncates toward zero)
  print(-7 % 3);         // 2
  print((-7).remainder(3)); // -1

  var level = 1;
  level++;               // 2
  level += 10;           // 12
  print(level);
}

The increment and decrement operators ++ and -- exist in prefix and postfix forms, and every arithmetic operator has a compound assignment version: +=, -=, *=, /=, ~/=, %=.

TypeScript Division and modulo (TypeScript stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Equality and relational operators

== and != test equality, and <, >, <=, >= compare order. For strings, numbers and most core types, == compares values, so 'a' + 'b' == 'ab' is true. For your own classes, == compares identity unless you override it (see the lesson on operator overloading later in this tutorial). To ask "are these the very same object?" use identical(a, b).

Dart has no ===. One == is all you need, because Dart never converts types behind your back: 1 == '1' is simply false.

Logical operators

&& (and), || (or) and ! (not) combine booleans. The first two short-circuit: the right side runs only when the left side has not already decided the result.

DART
bool expensiveCheck() {
  print('checking...');
  return true;
}

void main() {
  var ready = false;
  print(ready && expensiveCheck());  // false, expensiveCheck never runs
  print(!ready || expensiveCheck()); // true, still never runs

  var name = 'Ada';
  if (name.isNotEmpty && name[0] == 'A') {
    print('Starts with A');   // safe: [0] is only reached for non-empty names
  }
}

Short-circuiting is how you write guards: put the safety check on the left and the risky access on the right.

flowchart LR
    A["left && right"] --> B{"left is true?"}
    B -- "no" --> C["result is false<br/>(right is skipped)"]
    B -- "yes" --> D["result is the value of right"]

The && operator skips its right side whenever the left side is already false.

TypeScript Short-circuit evaluation (TypeScript stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Bitwise and shift operators

On integers you can work with individual bits:

Operator Meaning
& bitwise AND
| bitwise OR
^ bitwise XOR
~ bitwise NOT (flips every bit)
<< shift left
>> shift right, keeping the sign
>>> unsigned shift right (Dart 2.14 and later)

A classic use is a set of flags stored in one integer:

DART
const read = 1;    // 0b001
const write = 2;   // 0b010
const run = 4;     // 0b100

void main() {
  var permissions = read | write;     // 0b011 = 3
  print(permissions & write != 0);    // true  ... careful, see the note below
  permissions &= ~write;              // clear the write bit
  print(permissions);                 // 1
  print(1 << 4);                      // 16
  print(5 ^ 3);                       // 6
}

Unlike C, Dart's & binds tighter than !=, so permissions & write != 0 means (permissions & write) != 0, which is what you want. Readers coming from other languages may still doubt it, so write the parentheses anyway: (permissions & write) != 0.

TypeScript Flags with bit operators (TypeScript stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The cascade operator

Sometimes you want to call several methods or set several properties on the same object. The cascade .. does that without repeating the variable name. It evaluates each operation on the original object and, at the end, the whole expression is that object.

DART
class Pizza {
  String size = 'medium';
  final toppings = <String>[];
  void bake() => print('Baking a $size pizza with $toppings');
}

void main() {
  var pizza = Pizza()
    ..size = 'large'
    ..toppings.add('olives')
    ..toppings.add('basil')
    ..bake();
}
TEXT
Baking a large pizza with [olives, basil]

Without cascades you would write pizza.size = 'large'; and pizza.toppings.add(...) on separate lines. The null-aware cascade ?.. starts the chain only if the object is not null (the next lesson covers null safety). Remember that a cascade returns the receiver, not the result of the last call, so list..add(1) is the list, not void.

TypeScript What a cascade does (TypeScript stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Type test operators

Three operators deal with types at runtime:

  • value is Type is true if the value has that type.
  • value is! Type is the negation.
  • value as Type casts the value, and throws a TypeError if the value does not have that type.
DART
void main() {
  Object data = 'hello';

  if (data is String) {
    print(data.toUpperCase());   // data is promoted to String here
  }

  if (data is! int) {
    print('not an int');
  }

  var number = data as int;      // throws: String is not a subtype of int
}

Prefer is with a check over as: after is, Dart promotes the variable inside the if, so you rarely need a cast at all. You will see promotion in depth in Null Safety: Nullable and Non-Nullable Types and the type system tour in The Type System.

Precedence in practice

From strongest to weakest binding, the groups you use daily are: postfix and unary (x++, !x, -x), multiplicative (*, /, ~/, %), additive, shifts, &, ^, |, relational and type tests (<, is, as), equality, &&, ||, ??, the conditional ?:, cascade, and finally assignment. You do not need to memorize the table. When a line mixes more than two groups, add parentheses: it costs nothing and removes doubt.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does 7 / 2 evaluate to in Dart?

    The / operator always produces a double in Dart, so 7 / 2 is 3.5. Use 7 ~/ 2 for the truncated integer result 3.
  2. 2. Which condition compiles in Dart?

    Dart conditions must be of type bool. There is no truthiness, so numbers, strings and lists cannot be used directly.
  3. 3. What does the cascade .. return when used in var p = Pizza()..size = 'large';?

    A cascade evaluates the operations on the receiver and the expression's value is the receiver itself, so p holds the Pizza.
  4. 4. What is the value of -7 % 3 in Dart?

    Dart's % is a modulo that is non-negative for a positive divisor, so the result is 2. The sign-preserving remainder is available as (-7).remainder(3), which is -1.
  5. 5. Which operator should you usually prefer over as when you are not sure about a value's type?

    A check with is never throws and promotes the variable inside the branch, while as throws a TypeError if the type is wrong.

Summary

  • bool is true or false; Dart conditions must be booleans, there is no truthiness.
  • / always returns a double, ~/ truncates to an integer, and % is a modulo that is non-negative for a positive divisor.
  • && and || short-circuit, so put guards on the left; Dart has == but no ===.
  • Bitwise operators (&, |, ^, ~, <<, >>, >>>) work on integers; use parentheses to make mixed expressions clear.
  • The cascade .. runs several operations on one object and returns that object.
  • is, is! and as test and cast types; prefer is, which promotes the variable.

Next, learn how Dart keeps null under control in Null Safety: Nullable and Non-Nullable Types.