what is alternative of for in in darjs?

Issue

I am looking for the alternative of javascript for in in dart:js?

for example:

if('addEventListener' in event) {
event.addEventListener(change);
}

I used is operator, but it’s throwing an error in Safari becouse addEventListener does not exist in event.

if(event.addEventListener is Function) {
event.addEventListener(change);
}

Solution

Checking whether an object supports a specific method is not something you do in Dart. You should check that the object implements an interface which has that method.

In this example, you probably need:

if (event is EventTarget) {
  event.addEventListener("change", change);
}

If you think that the object might support the function, but you don’t actually know which interface it gets the function from, then you can do what you try here, using a dynamic lookup, but you need to catch the error you get if the function isn’t there.

dynamic e = event;  // if it isn't dynamic already.
Object addEventListener;
try {
  addEventListener = e.addEventListener;
} on Error {
  // ignore.
}
if (addEventListener is Function) {
  addEventListener(...);
}

Answered By – lrn

Answer Checked By – Jay B. (FlutterFixes Admin)

Leave a Reply

Your email address will not be published.