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,
}) {
  JavascriptRuntime? runtime;

  try {
    // Create JavaScript runtime
    runtime = getJavascriptRuntime();

    // Inject context variables
    _injectContext(runtime, context);

    // Wrap code to capture result
    final wrappedCode = '''
      (function() {
        ${code};
        return typeof result !== 'undefined' ? result :
               typeof valid !== 'undefined' ? valid :
               typeof value !== 'undefined' ? value : null;
      })()
    ''';

    // Evaluate with timeout
    final jsResult = runtime.evaluate(wrappedCode);

    // Convert to Dart
    return _convertToDart(jsResult);
  } catch (e) {
    print('JavaScript evaluation error (mobile): $e');
    return null;
  } finally {
    // Clean up runtime
    runtime?.dispose();
  }
}