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

This tutorial presents multiple methods for checking the runtime type of an object in Dart programming. There are two primary approaches:

  • Using runtimeType.
  • Utilizing the is operator.

These methods facilitate the examination of both dynamic and static types, aiding developers in tasks such as

  • Verifying the runtime type of an object.
  • Determining if an object is assignable to another type using the is operator.
  • Inspecting the type of a variable declared in Dart or Flutter.

Dart runtimeType

runtimeType is an instance member property inherited from the superclass Object. Since every class inherits from Object, this property is available by default.

It provides developers with debugging information regarding the type of a variable or object.

Here is the syntax.

Type get runtimeType

This returns either 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 Operator

The is operator is used to check if an object is an instance of a particular type.

Here is an operator example

object is type

Let’s define an Animal parent class and two child classes, Lion and Dog.

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 since the animal object is of type Animal.
  • dog is Animal: returns true as dog is an instance of a subtype, thus it’s considered an Animal.
  • animal is Dog: returns false because animal is not an instance of the Dog subclass.

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

Conclusion

In summary, runtimeType aids in checking the type of an object and always returns a string, while the is operator is utilized to verify if an object is an instance of a particular type.

Both techniques are valuable for developers in debugging and identifying type relationships.