Sample code for 30+ languages & platforms
Dart Requires Chilkat v11.4.0+

Call a JavaScript Function Returning a Boolean

See more JavaScript Examples

Demonstrates how to call a JavaScript function that returns a boolean.

Chilkat Dart Downloads

Dart
import 'package:chilkat/chilkat.dart';

void main() {
  // This is the JavaScript function we'll call:

  // function isEven(number) {
  //     return number % 2 === 0;
  // }

  final sbScript = CkStringBuilder();
  sbScript.append('function isEven(number) { return number % 2 === 0; }');

  final js = CkJs();

  final result = CkJsonObject();
  result.emitCompact = false;

  // Call Eval to add the function to the context's global object
  try {
    js.eval(sbScript, result);
  } on ChilkatException catch (e) {
    // Examine the result for an exception.
    print(result.emit());

    // Also examine the LastErrorText.
    print(e.lastErrorText);
    return;
  }

  // ------------------------------------------------------------------------------
  // Call the function isEven(8)

  final funcCall = CkJsonObject();

  // Create JSON specifying the function name and arguments

  // {
  //   "name": "isEven",
  //   "args": [ 8 ]
  // }

  funcCall.updateString('name', 'isEven');
  funcCall.updateInt('args[0]', 8);

  try {
    js.callFunction(funcCall, result);
  } on ChilkatException catch (e) {
    // Examine the result for an exception.
    print(result.emit());

    // Also examine the LastErrorText.
    print(e.lastErrorText);
    return;
  }

  print(result.emit());

  // Output:
  // {
  //   "type": "bool",
  //   "value": true
  // }

  final retval = result.boolOf('value');
  print(retval);

  // Output:
  // true
}