kris
kris

Reputation: 12570

How to tell the difference between an inherited class and its parent at runtime in Flutter/Dart

I wish to do a check if a particular variable is of type A, or of type B (which extends A).

In the debugger I can hover over my variable b and see that is is of type B - however in the code I don't know how to check that.

If I use b is A the value is true.
If I use b.runtimeType is B the value is false.

How can I check if a variable is a particular class B, distinct from the class A that it extends ?
class A {}
class B extends A {}

void main() {
  A a = A();
  B b = B();
  print('b is B : ${b is B}');
  print('b.runtimeType is B : ${b.runtimeType is B}');
  print('b is A : ${b is A}');
  print('b.runtimeType is A : ${b.runtimeType is A}');
}
b is B : true
b.runtimeType is B : false
b is A : true
b.runtimeType is A : false
What check could I do that would result in b (is) B : true and b (is) A : false ?

Upvotes: 1

Views: 312

Answers (1)

kris
kris

Reputation: 12570

I was given the answer while asking the question;

The type of a runtimeType property is actually something like '_type', but the value of it is the type, so a simple == comparison is what is needed to do the trick:

  print('b.runtimeType == B : ${b.runtimeType == B}');
  print('b.runtimeType == A : ${b.runtimeType == A}');
b.runtimeType == B : true
b.runtimeType == A : false

Upvotes: 1

Related Questions