Flutter runtimeType and is operator| Flutter runtime type of an object

This tutorial shows multiple ways how to check a runtime of an object.

In Dart programming, there are two ways we can know the type of an object or a variable.

  • runtimeType
  • is operator

This checks dynamic and static types and helps the developer to find the following things

  • Check a runtime type of an object
  • Object is assignable to another type using the is operator.
  • Check the type of a variable declared in Dart or Flutter.

Dart runtimeType

runtimeType is a property instance member available in a superclass( Object). Each class inherits an Object, so it provides this property by default.

This helps developers to get debugging information about the type of the variable or an object.

Here is the syntax.

Type get runtimeType

This returns a Static or dynamic type and the runtimeType instance member is not overridden in classes.

Example:

class Employee {}

main() {
  var emp = new Employee();
  var str = "hello";
  var number = 12;
  var float = 12.21;

  List<String> numbers = ["one", "two"];
  print(emp.runtimeType); //Employee
  print(str.runtimeType); //String
  print(number.runtimeType); //int
  print(float.runtimeType); //double
  print(numbers.runtimeType); //JSArray<String>
}

Dart is the operator

The is operator is used to checking if an object is an instance of the type.

Here is an operator example

object is type

Let’s create an Animal parent class and two child classes.

class Animal {
  eat() {
    print("Animal Eat");
  }
}

class Lion extends Animal {
  eat() {
    print("Lion Eat");
  }
}

class Dog extends Animal {
  eat() {
    print("Dog Eat");
  }
}

main() {
  Animal animal = new Animal();
  Dog dog = new Dog();

  print(animal.runtimeType); // Animal
  print(dog is Animal); // true
  print(animal is Animal); // true
  print(animal is Dog); // false
}

animal is Animal: returns true as the animal object is of Animal class type. dog is Animal returns true as the dog is an instance of a subtype, so it returns true. animal is Dog: return false animal is not the type of a class subclass of type.

is always returns true if the object is of the same type or subclass type.

Conclusion

As a result, runtimeType is used to check an object type and returns always a string. is the operator used to check an instance of a particular type? Both things help developers to debug the type of an object and identify the type of assignable types to subtypes.