239

Dart specification states:

Reified type information reflects the types of objects at runtime and may always be queried by dynamic typechecking constructs (the analogs of instanceOf, casts, typecase etc. in other languages).

Sounds great, but there is no instanceof-like operator. So how do we perform runtime type-checking in Dart? Is it possible at all?

11 Answers 11

325

The instanceof-operator is called is in Dart. The spec isn't exactly friendly to a casual reader, so the best description right now seems to be http://www.dartlang.org/articles/optional-types/.

Here's an example:

class Foo { }

main() {
  var foo = new Foo();
  if (foo is Foo) {
    print("it's a foo!");
  }
}
8
  • 2
    Looks like there is no mention of is operator at all in the specification. It's better to refere to the grammar file in Dart sources: code.google.com/p/dart/source/browse/trunk/dart/language/…
    – Volo
    Commented Oct 10, 2011 at 17:11
  • 4
    @Idolon, the is operator is defined on page 59 of the spec, section 10.30 'Type test'
    – Duncan
    Commented Oct 11, 2011 at 8:53
  • 14
    is and is! can be found in the Operators section of the Dart language tour.
    – SoftWyer
    Commented Jun 25, 2019 at 16:02
  • 5
    new syntax is getTypeName(dynamic obj) => obj.runtimeType; Commented Sep 28, 2019 at 7:53
  • 2
    Make sure you don't combine the two different methods here and end up with foo.runtimeType is String that screwed me up for a while. Commented Apr 11, 2022 at 0:19
83

Dart Object type has a runtimeType instance member (source is from dart-sdk v1.14, don't know if it was available earlier)

class Object {
  //...
  external Type get runtimeType;
}

Usage:

Object o = 'foo';
assert(o.runtimeType == String);
10
  • 32
    RuntimeType is only for debugging purposes and the application code shouldn't depend on it. It can be overridden by classes to return fake values and probably returns unusable values when transpiled to JS Commented Mar 11, 2016 at 21:33
  • 1
    Thanks for your remark, I'm pretty new to Dart, and I agree that runtimeType may be overriden by classes, although I can't think of a reason why they would. (external code can't set the value sinse it's a getter) Personally, I would stick to is and reflection.
    – sbedulin
    Commented Mar 11, 2016 at 22:47
  • 3
    It's fine this is mentioned here. It's not very obvious that runtimeType has these limitations. Commented Mar 12, 2016 at 8:43
  • 6
    @GünterZöchbauer comment is no longer true in Dart 2. It should be fine to use it now.
    – vovahost
    Commented Nov 13, 2019 at 14:33
  • 1
    I'm not sure why he thinks it's ok in Dart 2. Perhaps I missed something. Commented Nov 13, 2019 at 17:46
24

Simply use .runtimeType on the property like below,

print(unknownDataTypeProperty.runtimeType)
0
22

As others have mentioned, Dart's is operator is the equivalent of Javascript's instanceof operator. However, I haven't found a direct analogue of the typeof operator in Dart.

Thankfully the dart:mirrors reflection API has recently been added to the SDK, and is now available for download in the latest Editor+SDK package. Here's a short demo:

import 'dart:mirrors'; 

getTypeName(dynamic obj) {
  return reflect(obj).type.reflectedType.toString();
}

void main() {
  var val = "\"Dart is dynamically typed (with optional type annotations.)\"";
  if (val is String) {
    print("The value is a String, but I needed "
        "to check with an explicit condition.");
  }
  var typeName = getTypeName(val);
  print("\nThe mirrored type of the value is $typeName.");
}
4
  • Is Dart a statically typed language?
    – Lii
    Commented Jun 6, 2019 at 17:58
  • it is good solution but, we have error: Unsupported operation: dart:mirrors is no longer supported for web apps Commented Sep 28, 2019 at 7:50
  • @Lii This answer was written for Ecma TC52. See dart.dev/faq
    – Rob
    Commented Oct 25, 2019 at 21:53
  • Be aware that Flutter, if you're using that, disables reflection (because it breaks tree shaking).
    – Ian
    Commented Apr 14, 2021 at 18:26
21

There are two operators for type testing: E is T tests for E an instance of type T while E is! T tests for E not an instance of type T.

Note that E is Object is always true, and null is T is always false unless T===Object.

3
  • Could you explain what is meant by by T===Object? Dart doesn't have the triple equals operator, but you chose to use it rather than double equals, so I assume the difference has significance.
    – Matt C
    Commented Apr 10, 2019 at 17:02
  • 1
    @MattC That was written more than 7 years ago! I think what I meant was null is Object would be true but null is T false for any other type T. tbh though I haven't been near Dart for many years now so can't be certain.
    – Duncan
    Commented Apr 12, 2019 at 14:23
  • You save my day man! With this: var isAuthFailure = Failure is! AuthenticationFailure; Commented Jul 13, 2022 at 16:30
20

Exact type matching is done via runtimeType property. Checking if an instance or any of its parent types (in the inheritance chain) is of the given type is done via is operator:

class xxx {}

class yyy extends xxx {}

void main() {
  var y = yyy();
  
  print(y is xxx);
  print(y.runtimeType == xxx);
}

Returns:

true
false
1
  • you forgot to mention that print(y is yyy) returns true as well and that case "is" not 100% option to use this one everytime Commented Aug 8 at 12:07
15

Just to clarify a bit the difference between is and runtimeType. As someone said already (and this was tested with Dart V2+) the following code:

class Foo {
  @override
  Type get runtimeType => String;
}
main() {
  var foo = Foo();
  if (foo is Foo) {
    print("it's a foo!");
  }
  print("type is ${foo.runtimeType}");
  
}

will output:

it's a foo! 
type is String

Which is wrong. Now, I can't see the reason why one should do such a thing...

3

if(value is int ) Returns true if the type of the value is int, else if(value is! int )

2

T is The type

   print( T.runtimeType)

enter image description here


enter image description here

2
  • .runtimeType property does an exact type match.
  • is keyword matches on parent class types and class extension types
    class Aaa {}

    class Bbb extends Aaa {}
    
    void main() {
      var x = Bbb();
      
      print(x is Aaa);                  // true
      print(x is Bbb);                  // true
      print(x.runtimeType == Aaa);      // false
      print(x.runtimeType == Bbb);      // true
      print(x.runtimeType);             // Bbb
      print(x.runtimeType.runtimeType); // _Type
      print(x.runtimeType.toString());  // Bbb
    }

1

To check the type of a variable use runtimeType

void main() {
  int a = 10;
  print(a.runtimeType);
}

to check whether the type of a variable is the same as your expected use is or runtimeType

void main() {
  int a = 10;
  print(a.runtimeType == int); // true
  //or
  print(a is int); // true
}
1
  • Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
    – Community Bot
    Commented Feb 1, 2023 at 15:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.