Dart| Flutter How to: Find an object implements interface

In Dart, Class extends only one parent class and implements multiple interfaces.

Below are operators to check a class of a given object.

is checks a given object implements or extends interface or class, It checks parent class hierarchy and returns true if it follows inheritance. runtimeType: Returns the class of an object and gives the only current class of an object not the inheritance tree class

checking if an object implements interface in dart?

This example checks an object and implements interfaces.

In this example, Created two interfaces Shape and Shape1.

Create a Square class that implements Multiple interfaces(Shape,Shape1) Create a Circle that implements the single interface(Shape)

use the is operator in Dart to check whether an object implements a particular interface or not.

Here is an example program

void main() {
  var square = new Square();
  var circle = new Circle();

  print(square is Shape); //true
  print(square is Shape1); //true
  print(square.runtimeType); //Square

  print(circle is Shape); //true
  print(circle.runtimeType); //Circle
}

abstract class Shape {
  void display() {
    print("Shape");
  }
}

abstract class Shape1 {
  void display() {
    print("Shape");
  }
}

class Circle implements Shape {
  void display() {
    print("Circle");
  }
}

class Square implements Shape, Shape1 {
  void display() {
    print("Square");
  }
}

Output:

true
true
Square
true
Circle

How to check Object extends class in dart?

This checks if a given object extends the class or not.

In this example, Created two interfaces Animal and Animal.

Create a Lion class that implements Class(Animal), Since the implicit class is an interface in dart. Create a Cat that extends a single interface(Animal)

use the is operator in Dart to check whether an object extends a particular class or not.

Here is an example program

void main() {
  var lion = new Lion();
  var cat = new Cat();

  print(lion is Animal); //true
  print(lion is Animal1); //false
  print(lion.runtimeType); //Lion

  print(cat is Lion); //true
  print(cat.runtimeType); //Cat
}

class Animal {
  void display() {
    print("Animal");
  }
}

class Animal1 {
  void display() {
    print("Shape");
  }
}

class Lion implements Animal {
  void display() {
    print("Lion");
  }
}

class Cat extends Animal1 {
  void display() {
    print("Cat");
  }
}