乐闻世界logo
搜索文章和话题

What are some operators commonly used in Dart?

1个答案

1

1. Arithmetic operators

These operators perform basic mathematical operations:

  • +: Addition
  • -: Subtraction
  • *: Multiplication
  • /: Division (result is a floating-point number)
  • ~/: Integer division (result is an integer)
  • %: Modulo operation

For example:

dart
int a = 10; int b = 3; print(a + b); // 13 print(a - b); // 7 print(a * b); // 30 print(a / b); // 3.3333333333333335 print(a ~/ b); // 3 print(a % b); // 1

2. Relational operators

These operators are used for comparing two variables:

  • ==: Equality
  • !=: Inequality
  • >: Greater than
  • <: Less than
  • >=: Greater than or equal to
  • <=: Less than or equal to

For example:

dart
int x = 5; int y = 2; print(x == y); // false print(x != y); // true print(x > y); // true print(x < y); // false print(x >= y); // true print(x <= y); // false

3. Type test operators

Used for testing the type of a variable:

  • is: Checks if an object is of a specified type
  • is!: Checks if an object is not of a specified type

For example:

dart
var name = 'Alice'; print(name is String); // true print(name is! int); // true

4. Assignment operators

Used for assigning values to variables:

  • =: Basic assignment
  • +=: Addition assignment
  • -=: Subtraction assignment
  • *=: Multiplication assignment
  • /=: Division assignment
  • %=: Modulo assignment

For example:

dart
int num = 10; num += 5; // num = num + 5 print(num); // 15

5. Logical operators

Used for logical operations on boolean values:

  • &&: Logical AND
  • ||: Logical OR
  • !: Logical NOT

For example:

dart
bool isTrue = true; bool isFalse = false; print(isTrue && isFalse); // false print(isTrue || isFalse); // true print(!isTrue); // false

6. Conditional expression operators

  • ?:: Conditional expression (ternary operator)
  • ??: Null-aware operator (uses the right-hand expression if the left is null)

For example:

dart
var userName = null; var guestName = userName ?? 'Guest'; print(guestName); // Guest int income = 10000; String message = income > 5000 ? 'Good salary' : 'Average salary'; print(message); // Good salary

These are some commonly used operators in Dart along with usage examples. These operators are very useful in daily coding, helping us perform various logical checks, mathematical operations, and value manipulations.

2024年8月5日 12:53 回复

你的答案