evaluate method
Evaluates JavaScript code with the given context.
code - The JavaScript code to execute
context - Variables/data available to the JavaScript code
Returns the result of the JavaScript evaluation, or null if evaluation fails.
Example:
final result = evaluator.evaluate(
'data.price * data.quantity',
{'data': {'price': 10.0, 'quantity': 5}},
);
print(result); // 50.0
Implementation
@override
dynamic evaluate(String code, Map<String, dynamic> context) {
try {
// Set context variables
for (final entry in context.entries) {
runtime.evaluate('var ${entry.key} = ${_encodeValue(entry.value)};');
}
// Execute code
final result = runtime.evaluate(code);
if (result.isError) {
throw JsEvaluationException(
'JavaScript execution error',
result.stringResult,
);
}
return _decodeValue(result.rawResult);
} catch (e) {
throw JsEvaluationException('Failed to evaluate JavaScript', e);
}
}