[Flutter] Operator in Dart

2021-04-01 hit count image

Let's see how to use Dart to develop the app with Flutter. In this blog post, I'll introduce how to use Operators in Dart.

Blog series

This blog post is a series. You can see the other posts on the link below.

Outline

Let’s see what operators are in Dart and how to use them.

You can see the source code, that is introduced on this blog post, on the link below

Arithmetic operators

When you calculate the numbers, you can use the arithmetic operators like other languages.

void main() {
  double num1 = 4;

  print(num1 + 2);
  print(num1 - 2);
  print(num1 * 2);
  print(num1 / 2);
  print(num1 % 3);
  print(num1++);
  print(num1--);
  print(++num1);
  print(--num1);
  print(num1 += 1);
  print(num1 -= 1);
  print(num1 *= 1);
  print(num1 /= 2);
  print(num1 %= 3);
}

Comparison operators

You can use the Comparison operators in Dart like other langauges.

void main() {
  int num1 = 3;
  int num2 = 5;

  print(num1 > num2);
  print(num1 < num2);
  print(num1 >= num2);
  print(num1 <= num2);
  print(num1 == num2);
  print(num1 != num2);
}

Type comparison operators

You can compare the Type of the variable like below.

void main() {
  int num = 3;

  print(num is int);
  print(num is String);
  print(num is List);
}

You can check that the types are not the same as follows.

void main() {
  int num = 3;

  print(num is! int);
  print(num is! String);
  print(num is! List);
}

Logical operators

You can use the logical operators in Dart like other langauges.

void main() {
  print(true && true);
  print(true && false);
  print(false && true);
  print(false && false);
  print(true || true);
  print(true || false);
  print(false || true);
  print(false || false);
}

Null-aware operator

You can use ??= operator in Dart. This operator assigns the value only when the variable is null.

void main() {
  var name = null;
  name ??= 'Yakuza';
  print(name);

  name ??= 'Dev';
  print(name);
}

The name varialbe is not initialized, so it is assinged null. First ??= operator can assign the value because the name is null, but second ??= operator doesn’t assign because the variable is not null.

Completed

We’ve seen what operators are in Dart and how to use the operators. We’ve known that we can use the almost operators of the other languages in Dart.

Was my blog helpful? Please leave a comment at the bottom. it will be a great help to me!

App promotion

You can use the applications that are created by this blog writer Deku.
Deku created the applications with Flutter.

If you have interested, please try to download them for free.

Posts