Gurleen Sethi
Gurleen Sethi

Reputation: 3502

How to check if an object is of instance `Type`?

I have a function as follow

void (Type type, dynamic instance) {
  // Unable to do this
  if (instance is type) {
  }
}

I want to check if the instance passed is of the same type as the passed type. The type can be a base class and the instance can be the implementation of the base class, so just (instance.runtimeType == type) won't suffice.

Upvotes: 0

Views: 1200

Answers (2)

Rémi Rousselet
Rémi Rousselet

Reputation: 276881

You can't do so using a runtime Type object.

To achieve something similar, you'll have to use generic functions instead:

void foo<T>(dynamic instance) {
  if (instance is T) {

  }
}

Upvotes: 3

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657048

There is only a limited way to test that like using type.toString()

if('$type' == 'SomeClassName') 

Upvotes: 1

Related Questions