SafetyPin
SafetyPin

Reputation: 125

How to find out if a variable exists or not in Dart

In JavaScript, I can use "in" operator to check a variable exists or not. So, maybe this code works correctly.

index.html

<!DOCTYPE html>
<html>
 <head>
  <meta charset="utf-8">
  <title>Using in operator</title>
 </head>
 <body>
  <div id="div1">hello</div>
  <script>
   document.someValue = "testValue";
   if( 'someValue' in document ) {
    document.getElementById('div1').innerHTML = document.someValue;
   }else{
    document.getElementById('div1').innerHTML = "not found";
   }
  </script>
 </body>
</html>

As a result, The final content of div1 will be "testValue". However, Dart doesn't have "in" operator. In Dart, it is true that HtmlDocument class has contains() method. But, the argument type of the method is Node, not String. I also tried this code.

print( js.context['document'] );
print( js.context['document']['someValue'] );

" js.context['document'] " works well and returns instance of HtmlDocument object. However, " js.context['document']['someValue'] " totally does NOT work. This returns nothing or no error.

Is there any means to check variable existence in Dart? :-(

Thank you for reading!

Upvotes: 6

Views: 20465

Answers (3)

kris
kris

Reputation: 12580

I found simply checking if the value was null works fine.

if (js.context['document']['someValue'] != null) {
  // do stuff with js.context['document']['someValue']
} else {
  // that property doesn't exist
}

Upvotes: 3

lrn
lrn

Reputation: 71693

There is no simple way to check if an object has an arbitrary member.

If you expect a Dart object to have a field, you probably do so because you expect it to implement an interface which has that field. In that case, just check the type:

if (foo is Bar) { Bar bar = foo; print(bar.someValue); }

The properties of a Dart object won't change after it is created. Either it has the member, or it doesn't, and the type determines it.

If you expect the object to have the member, but you don't know the type that declares that member (then you are probably doing something a little too tricky, but) then you can just try using it inside a try catch.

var someValue = null;
try {
  someValue = foo.someValue;
} catch (e) {
  // Nope, wasn't there.
}

For real exploratory programming, you can use the dart:mirrors library.

InstanceMirror instance = reflect(foo);
ClassMirror type = instance.type;
MethodMirror member = type.instanceMembers[#someValue];
if (member != null && member.isGetter) {
  var value = instance.getField(#someValue).reflectee;  // Won't throw.
  // value was there.
} else {
  // value wasn't there.
}

Upvotes: 6

Alexandre Ardhuin
Alexandre Ardhuin

Reputation: 76233

Assuming you use dart:js you can use JsObject.hasProperty

js.context.hasProperty('someValue');

Upvotes: 1

Related Questions