Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

flutter

dart

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
}
like image 847
RahZun Avatar asked Jun 06 '20 05:06

RahZun


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
}
like image 172
Doruk Eren Aktaş Avatar answered Oct 16 '22 19:10

Doruk Eren Aktaş


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.

like image 26
jamesdlin Avatar answered Oct 16 '22 20:10

jamesdlin