5

Let's say I get two instances in my code and I don't know their types. How to check it?

If in Java, I can use this code:

a.getClass() == b.getClass()

But in Dart, I can't find similar methods. Although there is the dart:mirrors providing reflect(instance) function, which may let me do it, but I'm not sure if that's a correct solution since it looks complicated.

cubuspl42
  • 7,833
  • 4
  • 41
  • 65
Freewind
  • 193,756
  • 157
  • 432
  • 708

3 Answers3

5
a.runtimeType == b.runtimeType
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • 1
    Note that this might have false positives, because classes are allowed to override runtimeType. And in really contrived cases even a false negative. But for normal uses it should be fine. – Alan Knight Feb 05 '14 at 04:13
1

I think dart:mirrors (reflection) API helps you. Look at this page :

http://blog.dartwatch.com/2012/06/dartmirrors-reflection-api-is-on-way.html

Also you can look this question(with runtime solution)

How do I get the qualified name from a Type instance, in Dart?

Community
  • 1
  • 1
Semih Eker
  • 2,389
  • 1
  • 20
  • 29
0

if you want to compare a and b you can use

if(a.runtimeType == b.runtimeType);

but if you want to confirm that a is the type you want you need to do this

if(a.runtimeType.toString()=="DivElement");//a is a div for instance

because runtimeType's value is not a string

Saïd Tahali
  • 189
  • 10