Search code examples
darttypechecking

Dart type checking with type reference as variable


I am trying to type check in Dart with a Type reference stored as a variable. Something like this:

    class Thingamajig {}
    
    bool method(dynamic object) {
      var Type type = Thingamajig;
      if (object is type) { //gives error: type_test_with_non_type
        doSomething();
      }
    }

My use case requires the sub-type checking functionality of is, so runtimeType will not suffice. How can I accomplish this and eliminate the error?

EDIT: My true intent was to have the type as an instance variable on a Finder class implementation for a Flutter widget test. I can solve this problem with something like this:

if (type == MyClass && object is MyClass)
if (type == MyOtherClass && object is MyOtherClass)

or

switch (type) {
    case MyClass:
        if (object is MyClass) //do stuff
        break;
    case MyOtherClass:
        if (object is MyOtherClass) // do other stuff
        break;
}

but I was hoping for a cleaner option.


Solution

  • You can simply pass the type literal into the is expression, and it will work:

    var type = MyCustomClass;
    if (object is type) ...  // "type" is not a type
    if (object is MyCustomClass)  // works fine, including subtypes
    

    If you can't do that (maybe you want to pass in the type as a parameter), you can instead use a type parameter:

    bool checkType<T>(dynamic object) {
      if (object is T) ...  // works fine
    }
    

    However if you want your types to be dynamic at runtime, you're slightly out of luck. If this is what you want, perhaps some context on why you want that would help inform a better answer.