evaluateJS function

dynamic evaluateJS(
  1. String code,
  2. Map<String, dynamic> context, {
  3. int timeoutMs = 5000,
})

Implementation

dynamic evaluateJS(
  String code,
  Map<String, dynamic> context, {
  int timeoutMs = 5000,
}) {
  try {
    // Create a JavaScript context object
    final jsContext = js.JsObject.jsify(context);

    // Create a function that takes the context and returns the result
    final wrappedCode = '''
      (function(context) {
        ${_injectContext(context)}
        ${code};
        return typeof result !== 'undefined' ? result :
               typeof valid !== 'undefined' ? valid :
               typeof value !== 'undefined' ? value : null;
      })
    ''';

    // Evaluate the JavaScript code
    final jsFunction = js.context.callMethod('eval', [wrappedCode]);
    final result = jsFunction.apply([jsContext]);

    // Convert JS result to Dart
    return _convertToDart(result);
  } catch (e) {
    print('JavaScript evaluation error (web): $e');
    return null;
  }
}