23

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 2

22

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
}
3
  • Thank you so much. Yes this is very useful while decoding json response. But I also meant in normal Class objects in Dart. In python, I think we have hasattr()
    – RahZun
    Jun 6, 2020 at 6:23
  • Yes, but since you asked about JSON response body i did not think about PODO. Jun 6, 2020 at 6:25
  • 1
    But it was helpful. Thank you !! I think I should correct my question a bit
    – RahZun
    Jun 6, 2020 at 7:03
9

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.

6
  • 1
    How to check if object is a map (regardless of types of its key/values i.e. <String, String>)? The is operator seems to return type with <> which makes it different type. Oct 12, 2021 at 10:27
  • @MuhammadQasim You can check if an object is a Map via object is Map (which is shorthand for object is Map<dynamic, dynamic>).
    – jamesdlin
    Oct 12, 2021 at 16:54
  • Ah my bad. Just realized I was comparing the runtimeType instead of object itself which was giving false like this: var obj = {"abc": 123}; if(obj.runtimeType is Map) Thanks for helping. Oct 14, 2021 at 9:29
  • unfortunatly the first solution is not always working in Dart.
    – MwBakker
    Nov 28, 2022 at 11:32
  • @MwBakker Please elaborate. The first method should work. You should ensure that you use is on a local variable since only local variables are automatically type-promoted.
    – jamesdlin
    Nov 28, 2022 at 15:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.