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

Call a JavaScript Function Returning an Object

See more JavaScript Examples

Demonstrates how to call a JavaScript function that returns an object.

Chilkat Dart Downloads

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

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

  // function getSettings() {
  //     return {
  //         theme: "dark",
  //         notifications: true,
  //         version: 1.0
  //     };
  // }

  final sbScript = CkStringBuilder();
  sbScript.append('function getSettings() {');
  sbScript.append('    return {');
  sbScript.append('        theme: "dark",');
  sbScript.append('        notifications: true,');
  sbScript.append('        version: 1.0');
  sbScript.append('    };');
  sbScript.append('}');

  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 getSettings()

  final funcCall = CkJsonObject();

  // Create JSON specifying the function name and arguments
  // The function has no arguments, so we only specify the name.

  // {
  //   "name": "getSettings",
  // }

  funcCall.updateString('name', 'getSettings');

  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": "object",
  //   "value": {
  //     "theme": "dark",
  //     "notifications": true,
  //     "version": 1
  //   }
  // }

  // Examine the object's members
  print('theme: ${result.stringOf('value.theme')}');
  print('notifications: ${result.boolOf('value.notifications')}');
  print('version: ${result.intOf('value.version')}');

  // Output:
  // theme: dark
  // notifications: True
  // version: 1
}