Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Dart Operators

Dart Operators

Operators are symbols in a program that perform calculations, comparisons, and logical judgments.

This chapter systematically introduces the various operators in Dart, including arithmetic, relational, logical, assignment, and conditional operators, as well as type checking.


Arithmetic operators

Arithmetic operators are used to perform basic mathematical operations.

Example

void

main

(

)

{

 

int

a

=

10

;

 

int

b

=

3

;

  print

(

'a = $a, b = $b'

)

;

  print

(

'Addition a + b = ${a + b}'

)

;

   

// 13

  print

(

'Subtraction a - b = ${a - b}'

)

;

   

// 7

  print

(

'Multiplication a * b = ${a * b}'

)

;

   

// 30

  print

(

'Division a / b = ${a / b}'

)

;

   

// 3.333... (result is double)

  print

(

'Integer division a ~/ b = ${a ~/ b}'

)

;

 

// 3 (truncate, discard decimals)

  print

(

'Remainder a % b = ${a % b}'

)

;

   

// 1 (modulo operation)

  print

(

'Negation -a = ${-a}'

)

;

         

// -10 (unary minus)

}



a = 10, b = 3

加法 a + b = 13

减法 a - b = 7

乘法 a * b = 30

除法 a / b = 3.3333333333333335

整除 a ~/ b = 3

取余 a % b = 1

取反 -a = -10

Note: the / operator always returns a double type, even when both operands are int and divide evenly. If you only need an integer result, use the ~/ integer division operator.

Increment and decrement operators

Like most C-family languages, Dart supports ++ (increment) and -- (decrement).

Example

void

main

(

)

{

 

int

count

=

0

;

 

// Prefix ++: increment first, then use

  print

(

'Prefix ++: ${++count}'

)

;

 

// 1

 

// Postfix ++: use first, then increment

  print

(

'Postfix ++: ${count++}'

)

;

 

// 1 (count is still 1 at this point)

  print

(

'Now count = $count'

)

;

 

// 2

 

// Decrement works the same way

  print

(

'Prefix --: ${--count}'

)

;

 

// 1

  print

(

'Postfix --: ${count--}'

)

;

 

// 1

  print

(

'Now count = $count'

)

;

 

// 0

}



前置 ++: 1

后置 ++: 1

现在 count = 2

前置 --: 1

后置 --: 1

现在 count = 0

Prefix and postfix increment/decrement have the same effect when used alone, but behave differently inside expressions. Beginners are advised to avoid using them in expressions; writing them on a separate line is clearer.


Relational operators

Relational operators are used to compare two values, and the result is a bool value.

operator Meaning Example Result
== Equal 5 == 5 true
!= Not equal 5 != 3 true
> Greater than 5 > 3 true
< Less than 5 < 3 false
>= Greater than or equal to 5 >= 5 true
<= Less than or equal to 3 <= 5 true

Example

void

main

(

)

{

 

int

runoobScore

=

95

;

 

int

passLine

=

60

;

  print

(

'Score: $runoobScore, pass line: $passLine'

)

;

  print

(

'Did you pass? ${runoobScore >= passLine}'

)

;

  print

(

'Is it a perfect score? ${runoobScore == 100}'

)

;

 

// Strings can also be compared

  String a

=

'apple'

;

  String b

=

'banana'

;

  print

(

"'$a' == '$b'? ${a == b}"

)

;

 

// == checks whether values are equal

  String c

=

'RUNOOB'

;

  String d

=

'RUNOOB'

;

  print

(

"'$c' == '$d'? ${c == d}"

)

;

 

// true (same content)

}



分数: 95, 及格线: 60

及格了吗? true

满分了吗? false

'apple' == 'banana'? false

'RUNOOB' == 'RUNOOB'? true

In Dart, == compares whether the values of two objects are equal, not their reference addresses. This differs from Java -- in Dart you don't need the equals() method to compare strings.


Logical operators

Logical operators are used to combine multiple bool expressions, typically for conditional judgments.

operator Meaning Description
&& Logical AND Returns true only when both sides are true
|| Logical OR Returns true if either side is true
! Logical NOT Negation: true becomes false, false becomes true

Example

void

main

(

)

{

 

bool

isLoggedIn

=

true

;

 

bool

isAdmin

=

false

;

 

// && AND: both are true

  print

(

'Logged in and is admin: ${isLoggedIn && isAdmin}'

)

;

 

// false

 

// || OR: at least one is true

  print

(

'Logged in or is admin: ${isLoggedIn || isAdmin}'

)

;

 

// true

 

// ! NOT: negation

  print

(

'Not logged in: ${!isLoggedIn}'

)

;

 

// false

 

// Short-circuit evaluation: if the left side already determines the result, the right side won't execute

 

int

age

=

20

;

 

// age > 18 is already true, but the right side still needs to be checked

  print

(

'Adult and has permission: ${age >= 18 && isAdmin}'

)

;

 

// age < 18 is already false, the right side of && is skipped directly

  print

(

'Underage and has permission: ${age < 18 && isAdmin}'

)

;

}



登录且是管理员: false

登录或是管理员: true

未登录: false

成年且有权限: false

未成年且有权限: false

Dart uses short-circuit evaluation: for &&, if the left side is false, the right side is not evaluated; for ||, if the left side is true, the right side is not evaluated.

This feature can be used to avoid null pointer problems.

Example

Practical applications of short-circuit evaluation:

void

main

(

)

{

  String

?

username

;

 

// Safe check: username is not null and its length is greater than 3

 

// If username is null, the right side of && won't execute, avoiding null pointer errors

 

if

(

username

!=

null

&&

username.

length

3

)

{

    print

(

'Valid username'

)

;

 

}

else

{

    print

(

'Invalid username or too short'

)

;

 

}

}



用户名无效或太短


Assignment operators

You are already familiar with the basic assignment operator =.

Dart also provides compound assignment operators that simplify common "compute-then-assign" operations.

operator Equivalent form Example (when a=10)
+= a = a + b a += 3 → 13
-= a = a - b a -= 3 → 7
*= a = a * b a *= 3 → 30
/= a = a / b a /= 2 → 5.0
~/= a = a ~/ b a ~/= 3 → 3
%= a = a % b a %= 3 → 1

Example

void

main

(

)

{

 

int

score

=

0

;

 

// Add 10 points for each correct answer

  score

=

10

;

  print

(

'Correct on question 1: $score'

)

;

  score

=

10

;

  print

(

'Correct on question 2: $score'

)

;

 

// Deduct 5 points for a wrong answer

  score

=

5

;

  print

(

'Wrong on 1 question: $score'

)

;

 

// Double the score

  score

=

2

;

  print

(

'Bonus doubled: $score'

)

;

  print

(

'RUNOOB final score: $score'

)

;

}



答对第1题: 10

答对第2题: 20

答错1题: 15

奖励翻倍: 30

RUNOOB 最终得分: 30


Conditional operators: ?? and ??=

These two operators are designed specifically for handling null values and are an important part of Dart's null safety system.

?? null-coalescing operator

If the left expression is not null, return the left value; otherwise return the right value.

??= null-aware assignment operator

If the variable is currently null, assign the right value to it; otherwise leave it unchanged.

Example

void

main

(

)

{

 

// ?? null coalescing

  String

?

nickname

;

  String displayName

=

nickname

??

'RUNOOB user'

;

  print

(

displayName

)

;

 

// RUNOOB user

  nickname

=

'Little R'

;

  displayName

=

nickname

??

'RUNOOB user'

;

  print

(

displayName

)

;

 

// Little R

 

// Chained ?? is also possible

  String

?

a

;

  String

?

b

;

  String result

=

a

??

b

??

'Default value'

;

  print

(

result

)

;

 

// Default value

 

// ??= null-aware assignment

 

int

?

count

;

  count

??

=

0

;

 

// count is null, assign 0

  print

(

count

)

;

 

// 0

  count

??

=

100

;

 

// count is already 0 (not null), no assignment

  print

(

count

)

;

 

// 0 (unchanged)

}



RUNOOB 用户

小R

默认值

0

0

Ternary conditional operator ? :

This is Dart's only operator with three operands; it is a concise version of if-else.

Example

void

main

(

)

{

 

int

score

=

75

;

 

// Syntax: condition ? value if true : value if false

  String result

=

score

=

60

?

'Pass'

:

'Fail'

;

  print

(

'RUNOOB exam result: $result'

)

;

 

// Can be nested (but not recommended to exceed two levels, as readability suffers)

  String grade

=

score

=

90

?

'Excellent'

:

score

=

60

?

'Pass'

:

'Fail'

;

  print

(

'Rating: $grade'

)

;

}



RUNOOB 考试结果: 及格

评级: 及格


Type test operators: is and as

is is used to check whether an object belongs to a certain type, and as is used for type casting.

Example

void

main

(

)

{

 

// is: type check

 

var

name

=

'RUNOOB'

;

  print

(

'Is name a String? ${name is String}'

)

;

 

// true

  print

(

'Is name an int? ${name is int}'

)

;

       

// false

 

// is!: is not a certain type

  print

(

'Is name not an int? ${name is! int}'

)

;

     

// true

 

// as: type cast

  Object obj

=

'Hello, Dart!'

;

 

// Convert an Object type to String in order to use String's methods

  String str

=

obj

as

String

;

  print

(

str.

toUpperCase

(

)

)

;

 

// Safe type check + cast

  Object maybeString

=

42

;

 

if

(

maybeString

is

String

)

{

   

// In the branch where is evaluates to true, the variable is automatically "promoted" to that type

    print

(

maybeString.

length

)

;

 

// No as cast needed

 

}

else

{

    print

(

'Not a string, value is: $maybeString'

)

;

 

}

}



name 是 String 吗? true

name 是 int 吗? false

name 不是 int 吗? true

HELLO, DART!

不是字符串,值是: 42

Prefer using is for type checks. Inside a conditional branch where is is true, Dart automatically promotes the variable to the target type (Type Promotion), so no as cast is needed. Use as only when "you are sure of the type but the compiler cannot infer it".


Overview of operator precedence

When an expression contains multiple operators, Dart evaluates them in order from highest to lowest precedence.

If you are unsure about precedence, the safest approach is to use parentheses to make the evaluation order explicit.

Precedence operator Description
Highest () [] . ?. Parentheses, subscripts, member access
! ~ - ++ -- Unary operators
* / % ~/ Multiplication, division, remainder
+ - Additive
< <= > >= Relational comparison
== != Equality checks
&& Logical AND
|| Logical OR
?? Null coalescing
? : Ternary conditional
= += -= *= etc. Assignment (lowest)

Example

void

main

(

)

{

 

// Don't rely on precedence -- use parentheses to express intent clearly

 

int

result

=

(

(

10

5

)

2

)

(

8

~/

3

)

;

  print

(

'Calculation result: $result'

)

;

 

// 28

 

// Without parentheses, the result may be completely different

 

// 10 + 5 * 2 - 8 ~/ 3 would be 18 (multiplication/division before addition/subtraction)

 

int

result2

=

10

5

2

8

~/

3

;

  print

(

'Without parentheses: $result2'

)

;

 

// 18

}



计算结果: 28

不加括号: 18