Home > Net >  Dart type_test_with_non_type when storing type in variable
Dart type_test_with_non_type when storing type in variable

Time:11-14

In my Flutter app I want to build this function:

bool isValidType(element, Type cls) {
  return element is cls;
}

The issue with this is: The name 'cls' isn't a type and can't be used in an 'is' expression. Try correcting the name to match an existing type. dart(type_test_with_non_type)

element is dynamic, but I expect it to be an Object of a class that extends the class Element (like class Node extends Element). The way I want to be able to use this function is:

isValidType(node, Node) -> true
isValidType(node, Element) -> true

I first thought I could do this:

bool isValidType(element, Type cls) {
  return element.runtimeType == cls;
}

But the problem with that is that for the examples provided above it returns the following:

isValidType(node, Node) -> true
isValidType(node, Element) -> false

The reason is of course that the runtimeType of node is Node and not Element.

What do I have to change in the function provided first to work for my requirements?

CodePudding user response:

There currently isn't much you can do with a Type object. The general recommendation is to avoid using them.

In your case, if you want to check against types known at compilation-time, you could make isValidType a generic function instead:

bool isValidType<T>(dynamic element) => element is T;

and then use isValidType<Node>(node) or isValidType<Element>(node). However, I don't think such a function adds anything, so you might as well replace isValidType<Node>(Node) with node is Node at the callsite.

  • Related