js-interop testing if javascript object has a property

Issue

Is it possible to test if a javascript object contains a property?

I’m currently wrapping try/catch for each property I’d like to access. I dont think this is an efficient way to check if properties exist on the object.

Solution

Using trycatch is the more efficient way to check that because there’s only one exchange between Dart and Js.


An other way could be to handle your javascript object like a Dart Map with :

import 'package:js/js.dart' as js;
import 'package:js/js_wrapping.dart' as jsw;

main() {
  final myProxy = ...;
  Map<String, dynamic> myProxyAsMap = jsw.JsObjectToMapAdapter.cast(proxy);
  Iterable<String> keys = myProxyAsMap.keys;
}

But it is less efficient to check if keys.contains("key") than to use the trycatch way. Moreover if you intensively use this keys consider to copy the List with a keys = myProxyAsMap.keys.toList(). Actually myProxyAsMap.keys is still baked by an underlying js array. The .toList() will create a real Dart List and prevent Dart-js exchanges.

Answered By – Alexandre Ardhuin

Answer Checked By – Marie Seifert (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *