How to do run-time type checking in Dart

Type checking in Dart :

If we are not declaring the type of a variable, we can assign any type to it. The compiler will not throw any error. Only in run-time, we will get type-mismatched.

Dart also provides one way to check the type during run-time. is and is! operators are used to check the type of a variable in dart. For example :

main(List<string> args) {
  var value = 2;
  print(value is int);
  print(value is! int);
}

It will print :

true
false

Dart type checking

This operator is equal to JavaScript’s instanceOf operator.

Example with custom class objects :

is and is! can be used with any custom class objects. For example :

class Student{
}
main(List<string> args) {
  var student = Student();
  print(student is Student);
}

It will print true as the output.

Type checking with generics :

Let’s consider the below example :

main(List<string> args) {
  var numList = List<int>();
  print(numList is List);
  print(numList is List<string>);
  print(numList is List<int>);
}

It will print :

true
false
true

This is one advantage of dart if we compare it to Java. In Java, we can’t check if an object is of type List, we can only check if it is of type List or not.

Similar tutorials :