Is there a Dart function to check if an object has a particular attribute or method?

Viewed 9428

Problems:

i) When checking if the normal Class object in Dart has particular property?

ii) When decoding JSON response body from api, How to check if an object has particular properties in DART?

e.g. In Javascript, there is "hasOwnProperty"

if (obj.hasOwnProperty('property')) {
    // do something
}
2 Answers

You can use bool containsKey(Object key);. Checkout documentation for more information. Also here you can find a related post.

if (obj.containsKey('property')) {
    // do something
}

Dart is strongly typed; you should check if the Object is of the type you want before calling methods on it:

if (obj is ClassWithProperty) {
  print(obj.property);
}

I would not recommend it, but you could disable type-checking by using a dynamic type:

var hasProperty = false;
try {
  (obj as dynamic).property;
  hasProperty = true;
} on NoSuchMethodError {
}

but catching Error types is frowned upon.

Related