dartToJsValue function

JSAny? dartToJsValue(
  1. Object? value
)

Converts a Dart value into its corresponding JavaScript interop representation (JSAny).

Handles recursive conversion of nested Dart data structures into native JavaScript types for setting rich DOM element properties on Custom Elements and Web Components:

  • Primitives (String, bool, int, double) are converted via .toJS.
  • List is recursively converted to a JavaScript JSArray.
  • Map is recursively converted to a JavaScript JSObject with string keys.
  • Closures (void Function(), Object? Function(), void Function(Object?), Object? Function(Object?)) are converted to JSFunction callbacks with automatic bidirectional argument and return value conversion via jsToDartValue and dartToJsValue.
  • Existing JSAny instances pass through untouched.
  • Other unhandled Dart types fall back to calling toString().toJS.

Used internally by customElement when setting properties on live DOM elements.

final jsObj = dartToJsValue({
  'title': 'Release v1.0',
  'tags': ['web', 'bloom', 'dart'],
  'config': {'active': true, 'retries': 3},
});

Implementation

JSAny? dartToJsValue(Object? value) {
  if (value == null) return null;
  // An already-converted JS value passes through untouched. The analyzer warns
  // that `is JSAny` on a Dart `Object` is not guaranteed platform-consistent,
  // but the alternative here is worse: without this the value would fall
  // through to the `toString()` branch below and be stringified.
  // ignore: invalid_runtime_check_with_js_interop_types
  if (value is JSAny) return value;
  if (value is String) return value.toJS;
  if (value is bool) return value.toJS;
  if (value is int) return value.toJS;
  if (value is double) return value.toJS;
  if (value is List) {
    final list = <JSAny?>[];
    for (final item in value) {
      list.add(dartToJsValue(item));
    }
    return list.toJS;
  }
  if (value is Map) {
    final obj = _newJsObject();
    for (final entry in value.entries) {
      _reflectSet(obj, entry.key.toString(), dartToJsValue(entry.value));
    }
    return obj;
  }
  if (value is Function) {
    if (value is void Function()) {
      return (() => value()).toJS;
    }
    if (value is Object? Function()) {
      return (() => dartToJsValue(value())).toJS;
    }
    if (value is void Function(Object?)) {
      return ((JSAny? a) => value(jsToDartValue(a))).toJS;
    }
    if (value is Object? Function(Object?)) {
      return ((JSAny? a) => dartToJsValue(value(jsToDartValue(a)))).toJS;
    }
  }
  return value.toString().toJS;
}