7. Operators

We all know that high-level computer languages have similar operators, so let’s take a look at what Dart has.

When operators are used, expressions can be created. Here are some examples of operator expressions:

a++
a + b
a = b
a == b
c ? a : b
a is T
Copy the code

In the operator table, each operator has precedence over the operator in the row following it. For example, the % operator has precedence over the == operator, which has precedence over the logical and && operators. This priority means that the following two lines of code execute the same way:

// Parentheses improve readability.
if ((n % i == 0) && (d % i == 0)) ...
// Harder to read, but equivalent.
if (n % i == 0 && d % i == 0) ...

Copy the code

Arithmetic operator

Dart supports the usual arithmetic operators, as shown in the following table.

To test whether two objects x and y represent the same thing, use the == operator. (In rare cases where you need to know whether two objects are identical, use the identical() function.) Here’s how the == operator works:

  • If x or y is null, return true if both are null; If only one is null, false is returned.
  • Returns the result of calling the method x.==(y). (Yes, operators such as == are methods called on the first operand. You can even override many operators, including ==)
assert(2 == 2); assert(2 ! = 3); assert(3 > 2); assert(2 < 3); assert(3 >= 3); assert(2 <= 3);Copy the code

The operator

As, is, is! Operators are handy for checking types at run time.

When obj is an implementation of the specified interface T, then obj is T is true. For example, obj is Object is always true. Use the AS operator to cast an object to a specific type. In general, you should do an IS test on an object before shortening its use.

if (emp is Person) {
  // Type check
  emp.firstName = 'Bob';
}
Copy the code

You can shorten the code using the AS operator:

(emp as Person).firstName = 'Bob';
Copy the code

Note that these two pieces of code are not identical. If the EMP is null or not a Person, then the first example (with IS) does nothing; The second example (with AS) throws an exception.

The assignment operator

As you can see, you can specify values using the = operator. To assign only when the variable is null, use?? = operator.

// Assign value to a a = value; // Assign value to b if b is null; Otherwise, b stays the same until b is null. Otherwise, b stays the same until B is null. = value;Copy the code

Compound assignment operators (such as +=) combine operations with assignments.

Logical operator

You can invert or combine Boolean expressions using logical operators.

if (! done && (col == 0 || col == 3)) { // ... Do something... }Copy the code

Conditional expression

Dart has two operators that make it easy to get results that require if-else expressions: condition? Expr1: expr2 If condition is true, expr1 is evaluated (and its value is returned); Otherwise, the value of expr2 is computed and returned. expr1 ?? Expr2 If expr1 is not null, the value is returned. Otherwise, the value of expr2 is computed and returned.

When you need to assign values from Boolean expressions, consider using? :

var visibility = isPublic ? 'public' : 'private';
Copy the code

If Boolean expressions test for NULL, consider using??

String playerName(String name) => name ?? 'Guest';
Copy the code

Cascade symbol (..)

Cascades(..) Allows you to perform a series of operations on the same object. In addition to function calls, you can also access fields on the same object. This usually saves you the step of creating temporary variables and allows you to write more fluid code.

querySelector('#confirm') // Get an object. .. text = 'Confirm' // Use its members. .. classes.add('important') .. onClick.listen((e) => window.alert('Confirmed! '));Copy the code

The first method call querySelector() returns a selector object. The code following the cascading notation operates on this selector object, ignoring any subsequent values that may be returned.

The previous example is equivalent to:

var button = querySelector('#confirm'); button.text = 'Confirm'; button.classes.add('important'); button.onClick.listen((e) => window.alert('Confirmed! '));Copy the code

You can also nest cascades:

final addressBook = (AddressBookBuilder() .. name = 'jenny' .. email = '[email protected]' .. phone = (PhoneNumberBuilder() .. number = '415-555-0100' .. label = 'home') .build()) .build();Copy the code

Be careful to construct cascades on functions that return actual objects. For example, the following failure code:

var sb = StringBuffer(); sb.write('foo') .. write('bar'); // Error: method 'write' isn't defined for 'void'.Copy the code

Calling sb.write() returns void, however you cannot construct a cascade on void

Note: Strictly speaking, the cascading “double dot” symbol is not an operator. It’s just part of the Dart syntax.