jsToDartValue function

Object? jsToDartValue(
  1. JSAny? jsVal
)

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

Recursively converts JavaScript types into native Dart data structures:

  • JSString is converted to a Dart String.
  • JSBoolean is converted to a Dart bool.
  • JSNumber is converted to a Dart int if it represents a whole integer, or double otherwise.
  • JSArray is recursively converted to a Dart List<Object?>.
  • JSObject is recursively converted to a Dart Map<String, Object?> by enumerating keys via Object.keys. If an object's keys cannot be extracted, the original jsVal is returned.

Used internally by CustomElementEvent to unwrap event.detail payloads into typed Dart values.

final dartData = jsToDartValue(customEventDetail);
if (dartData is Map<String, Object?>) {
  print('Item name: ${dartData['name']}');
}

Implementation

Object? jsToDartValue(JSAny? jsVal) {
  if (jsVal == null) return null;
  if (jsVal.isA<JSString>()) return (jsVal as JSString).toDart;
  if (jsVal.isA<JSBoolean>()) return (jsVal as JSBoolean).toDart;
  if (jsVal.isA<JSNumber>()) {
    final d = (jsVal as JSNumber).toDartDouble;
    if (d == d.roundToDouble() && !d.isInfinite && !d.isNaN) {
      return d.toInt();
    }
    return d;
  }
  if (jsVal.isA<JSArray<JSAny?>>()) {
    // `toDart` rather than JSArray's index/length operators, which require
    // SDK 3.6.0 while this package declares >=3.4.0.
    final arr = (jsVal as JSArray<JSAny?>).toDart;
    return [for (final item in arr) jsToDartValue(item)];
  }
  if (jsVal.isA<JSObject>()) {
    final obj = jsVal as JSObject;
    try {
      final keys = _jsObjectKeysRaw(obj).toDart;
      final map = <String, Object?>{};
      for (final k in keys) {
        final key = k.toDart;
        map[key] = jsToDartValue(_reflectGet(obj, key));
      }
      return map;
    } catch (_) {
      return jsVal;
    }
  }
  return jsVal;
}