JavaScript interop with dart:js_interop
suggest changedart:js_interop is how Dart code calls JavaScript and how JavaScript calls Dart. It became stable in Dart 3.3 and replaced the older package:js, dart:js, dart:js_util and dart:html. The same interop code compiles with both web compilers: dart compile js (dart2js) and dart compile wasm (dart2wasm).
The model is built on extension types:
- you declare JavaScript functions and properties as
externalmembers annotated with@JS - you wrap JavaScript objects in extension types whose representation type is
JSObject - values crossing the boundary have static JS types such as
JSString,JSArrayandJSPromise, and you convert them explicitly with.toJSand.toDart
This article covers:
- calling global JavaScript functions and reading globals
- the JS types and conversions
- wrapping JavaScript classes and creating object literals
- passing callbacks both ways, promises and futures
- type checks with
isA<T>() - exposing Dart objects to JavaScript with
@JSExport - DOM programming with
package:webinstead ofdart:html - migrating from
package:jsanddart:js_util
The examples were run with Dart 3.13.4 and Node 24, except the DOM example, which ran in headless Edge. Some APIs are newer than 3.3: isA (3.4), JSArray.length and [] (3.6), JSArray.add (3.10), JSSymbol well-known symbols (3.11), JSIterable and jsIdentical (3.12), and JSObject.getPrototypeOf (3.13).
The old articles in this chapter (Dart-JavaScript interoperability, Wrapping JavaScript classes/namespaces, Passing object literals, Calling a global function) use package:js. Use the approach below for new code.
Running the examples
Each example is a file in bin/ of a small package. The web dependency is only needed for the DOM example:
# pubspec.yaml
name: jsi
environment:
sdk: ^3.13.0
dependencies:
web: ^1.1.1
Compile with dart2js and run the output with Node:
$ dart compile js -o out/globals.js bin/globals.dart
$ node -r ./preamble.js out/globals.js
dart2js targets browsers and expects a global named self. Node only has globalThis, so async code fails with ReferenceError: self is not defined. A one-line preamble, loaded with node -r, fixes that:
globalThis.self ??= globalThis;
Some examples call JavaScript code of their own. Those files are also loaded with -r before the Dart program.
Calling global functions
An external top-level function, getter, setter or variable with @JS() maps to a property of globalThis with the same name. Pass a string to @JS to use a different name or a dotted path:
import 'dart:js_interop';
// Top-level JavaScript functions and properties.
@JS('parseInt')
external int parseInt(String s, [int radix]);
@JS('Math.max')
external double max(double a, double b);
@JS('Math.PI')
external double get pi;
@JS('JSON.stringify')
external String stringify(JSAny? value);
// Reading and writing a global variable.
@JS()
external String? appName;
void main() {
print(parseInt('ff', 16));
print(max(3, 7.5));
print(pi);
print(stringify('quote " me'.toJS));
print(appName);
appName = 'demo';
print(appName);
}
Output:
255
7.5
3.141592653589793
"quote \" me"
null
demo
Things to notice:
@JS('Math.max')readsMathfromglobalThis, thenmaxfrom it. The Dart namemaxcan be anything.- Primitive Dart types (
String,int,double,num,bool) are allowed directly in external signatures. The compiler converts them for you. - An optional argument you leave out isn't passed at all:
parseInt('ff')calls JavaScript with one argument, soarguments.lengthis 1. Passingnullexplicitly does passnull. - An
externalvariable gives you both a getter and a setter. Use a nullable type when the global may beundefined: JavaScriptnullandundefinedboth become Dartnull. stringifytakesJSAny?, the top type of all JavaScript values. A DartStringisn't aJSAny, so it's converted with.toJS.
Only JS types, primitives, void and ExternalDartReference (an opaque Dart object) may appear in external signatures. Anything else is a compile error, which prevents silent, expensive conversions:
Error: External JS interop member contains invalid types in its function signature: 'void Function(*List<int>*)'.
JS types and conversions
dart:js_interop defines extension types for JavaScript values:
| JS type | Dart to JS | JS to Dart |
|---|---|---|
JSString |
'a'.toJS |
.toDart gives String |
JSNumber |
1.toJS, 1.5.toJS |
.toDartInt, .toDartDouble |
JSBoolean |
true.toJS |
.toDart |
JSArray<T> |
list.toJS (elements must be JS types) |
.toDart gives List<T> |
JSPromise<T> |
future.toJS |
.toDart gives Future<T> |
JSFunction |
dartFunction.toJS |
.callAsFunction(...) |
JSUint8Array and other typed arrays |
uint8List.toJS |
.toDart gives Uint8List |
JSBoxedDartObject |
obj.toJSBox (opaque to JS) |
.toDart |
Their supertypes are JSAny (any value except null/undefined) and JSObject (any object). jsify() and dartify() convert JSON-like data (maps, lists, strings, numbers, booleans) in one deep, slow step:
import 'dart:js_interop';
@JS('JSON.parse')
external JSAny? parse(String json);
@JS('JSON.stringify')
external String stringify(JSAny? value);
void main() {
// Dart -> JS
JSString s = 'hello'.toJS;
JSNumber n = 42.toJS;
JSBoolean b = true.toJS;
JSArray<JSNumber> arr = [1.toJS, 2.toJS, 3.toJS].toJS;
print(stringify(arr));
// JS -> Dart
String s2 = s.toDart;
int i = n.toDartInt;
double d = n.toDartDouble;
bool b2 = b.toDart;
List<JSNumber> list = arr.toDart;
print('$s2 $i $d $b2 ${list.map((e) => e.toDartInt * 10)}');
// Deep conversion of JSON-like data
final js = {'name': 'Ann', 'tags': ['a', 'b'], 'age': 30}.jsify();
print(stringify(js));
final dart = parse('{"x": 1, "y": [true, null, "z"]}').dartify() as Map;
print(dart);
print(dart['y'] is List);
// toDartInt checks that the number is an integer
try {
print(1.5.toJS.toDartInt);
} catch (e) {
print('error: $e');
}
}
Output:
[1,2,3]
hello 42 42 true (10, 20, 30)
{"name":"Ann","tags":["a","b"],"age":30}
{x: 1, y: [true, null, z]}
true
error: TypeError: 1.5: type 'double' is not a subtype of type 'int'
list.toJS and arr.toDart may copy or wrap, depending on the compiler. Don't rely on changes to one being visible in the other.
The numbers show a real difference between the compilers. In dart2js every number is a JavaScript number, so 42.toJS.toDartDouble prints 42. Compiled to Wasm, the same program prints 42.0, and dartify() gives {x: 1.0, ...} because JSON numbers become double. The error for 1.5.toJS.toDartInt is also different (Invalid argument(s): JS value is not integer). Use toDartInt when you expect an integer, and don't print JavaScript numbers in tests that must pass on both compilers.
Wrapping JavaScript classes with extension types
To use a JavaScript class, declare an extension type over JSObject and add external members:
- an
externalconstructor calls the JavaScript constructor withnew - an
external factoryorexternal staticmember calls a static member of the class externalgetters, setters, fields and methods map to properties and methods of the instance- members without
externalare ordinary Dart code that runs on the wrapper
The extension type's name (or its @JS('...') rename) is the JavaScript class name used for constructors and static members. Here is a wrapper for the built-in URL class and for a small class written in JavaScript:
// counter.js: a plain JavaScript class, loaded before the Dart code
class Counter {
static created = 0;
constructor(label, start = 0) {
this.label = label;
this.value = start;
Counter.created++;
}
increment(by = 1) {
this.value += by;
return this.value;
}
static zero(label) {
return new Counter(label, 0);
}
}
globalThis.Counter = Counter;
import 'dart:js_interop';
// Wraps the built-in URL class.
extension type URL._(JSObject _) implements JSObject {
external URL(String url, [String base]);
external String get hostname;
external String get pathname;
external URLSearchParams get searchParams;
external String get hash;
external set hash(String value);
}
extension type URLSearchParams._(JSObject _) implements JSObject {
external String? get(String name);
external void append(String name, String value);
@JS('toString')
external String asString();
}
// Wraps the Counter class from counter.js.
extension type Counter._(JSObject _) implements JSObject {
external Counter(String label, [int start]);
external factory Counter.zero(String label);
external static int get created;
external String get label;
external int value;
external int increment([int by]);
// Non-external members are ordinary Dart code.
bool get isEven => value.isEven;
}
void main() {
final url = URL('/docs/intro?lang=dart&v=3', 'https://example.com');
print(url.hostname);
print(url.pathname);
print(url.searchParams.get('lang'));
print(url.searchParams.get('missing'));
url.searchParams.append('page', '2');
url.hash = 'top';
print(url.searchParams.asString());
print(url);
final c = Counter('clicks', 10);
c.increment();
c.increment(5);
print('${c.label} = ${c.value}, even: ${c.isEven}');
c.value = 0;
final z = Counter.zero('other');
print('${z.label} = ${z.value}');
print('created: ${Counter.created}');
}
Run it with node -r ./preamble.js -r ./counter.js out/classes.js:
example.com
/docs/intro
dart
null
lang=dart&v=3&page=2
https://example.com/docs/intro?lang=dart&v=3&page=2#top
clicks = 16, even: true
other = 0
created: 2
URLSearchParams.toString is renamed with @JS('toString'), because declaring a toString member that returns a different value would be confusing. Calling print(url) still works: it calls JavaScript's toString and prints the full URL.
implements JSObject makes the wrapper usable wherever a JSObject (or JSAny) is expected, for example when passing it to JSON.stringify. An extension type has no runtime cost: at runtime url is the JavaScript URL object itself, not a Dart object that holds it.
Namespaces
To wrap a whole namespace, put @JS('name') on the library directive. Every top-level interop declaration and extension type in that file is then looked up on that object instead of on globalThis:
// All declarations in this library are looked up on globalThis.Intl.
@JS('Intl')
library;
import 'dart:js_interop';
extension type NumberFormat._(JSObject _) implements JSObject {
external NumberFormat(String locale, [NumberFormatOptions options]);
external String format(num value);
}
extension type NumberFormatOptions._(JSObject _) implements JSObject {
external factory NumberFormatOptions({String style, String currency});
}
@JS()
external JSArray<JSString> getCanonicalLocales(String locale);
import 'dart:js_interop';
import 'package:jsi/intl.dart';
void main() {
final eur = NumberFormat(
'de-DE',
NumberFormatOptions(style: 'currency', currency: 'EUR'),
);
print(eur.format(1234.5));
print(NumberFormat('en-IN').format(12345678));
print(getCanonicalLocales('EN-us').toDart.first.toDart);
}
Output (the space before € is a non-breaking space):
1.234,50 €
1,23,45,678
en-US
Top-level external members still need their own @JS(). Without it, compilation fails with Only JS interop members may be 'external'.
Object literals
Many JavaScript APIs take an options object. Declare an extension type with an external factory that has only named parameters: calling it creates a plain JavaScript object ({...}) with one property per argument that you pass. There's no @anonymous annotation any more.
For objects with properties that aren't known in advance, use JSObject() with the [], []=, has, getProperty and callMethod helpers from dart:js_interop_unsafe:
import 'dart:js_interop';
import 'dart:js_interop_unsafe';
@JS('JSON.stringify')
external String stringify(JSAny? value);
// An object literal type: no JS class behind it.
extension type ChartOptions._(JSObject _) implements JSObject {
external factory ChartOptions({
String title,
bool responsive,
int? width,
Padding padding,
});
external String get title;
external bool? get responsive;
external int? get width;
}
extension type Padding._(JSObject _) implements JSObject {
external factory Padding({int top, int left});
}
void main() {
final opts = ChartOptions(
title: 'Sales',
width: null,
padding: Padding(top: 4, left: 8),
);
print(stringify(opts));
print('${opts.title} ${opts.responsive} ${opts.width}');
print(opts.has('width'));
print(opts.has('responsive'));
// Dynamic property access with dart:js_interop_unsafe
final o = JSObject();
o['id'] = 7.toJS;
o['name'] = 'widget'.toJS;
print(stringify(o));
print((o['name'] as JSString).toDart);
print(o.getProperty<JSNumber>('id'.toJS).toDartInt);
final object = globalContext['Object'] as JSObject;
print(stringify(object.callMethod('keys'.toJS, o)));
}
Output:
{"title":"Sales","width":null,"padding":{"top":4,"left":8}}
Sales null null
true
false
{"id":7,"name":"widget"}
widget
7
["id","name"]
An argument you leave out isn't set at all (has('responsive') is false), while passing null explicitly sets the property to null. This matters for APIs that check 'key' in options.
dart:js_interop_unsafe is called unsafe because the property names are strings that the compiler can't check. Prefer typed extension types and use it for truly dynamic objects.
Callbacks
A JavaScript API that takes a callback needs a JavaScript function. Convert a Dart function with .toJS. Its parameter and return types must be JS types or primitives, just like external signatures. In the other direction, call a JSFunction with callAsFunction(thisArg, ...args):
// lib.js: JavaScript functions used by the Dart examples
globalThis.applyTwice = (f, x) => f(f(x));
globalThis.makeAdder = (n) => (x) => x + n;
globalThis.loadUser = async (id) => {
await new Promise((resolve) => setTimeout(resolve, 10));
if (id < 0) throw new Error(`bad id ${id}`);
return { id, name: `user${id}` };
};
// Calls a function that Dart stores in globalThis.fetchGreeting.
globalThis.callGreeting = async (name) => {
const text = await globalThis.fetchGreeting(name);
return `JS got: ${text}`;
};
import 'dart:js_interop';
@JS()
external int applyTwice(JSFunction<int Function(int)> f, int x);
@JS()
external JSFunction makeAdder(int n);
@JS('setTimeout')
external void setTimeout(JSFunction callback, int ms);
extension type JSNumberArray._(JSArray<JSNumber> _) implements JSArray<JSNumber> {
external JSNumberArray map(JSFunction callback);
external JSNumberArray filter(JSFunction callback);
external String join([String separator]);
}
void main() {
// Dart function -> JS function
int square(int x) => x * x;
print(applyTwice(square.toJS, 3));
final nums = JSNumberArray._([1.toJS, 2.toJS, 3.toJS, 4.toJS].toJS);
final result = nums
.filter(((JSNumber n) => n.toDartInt.isEven).toJS)
.map(((JSNumber n, int index) => (n.toDartInt * 100 + index).toJS).toJS);
print(result.join(', '));
// JS function -> call it from Dart
final add5 = makeAdder(5);
final r = add5.callAsFunction(null, 10.toJS) as JSNumber;
print(r.toDartInt);
setTimeout((() => print('timer fired')).toJS, 5);
}
Run with node -r ./preamble.js -r ./lib.js out/callbacks.js:
81
200, 401
15
timer fired
Note:
- JavaScript passes
(element, index, array)tofiltercallbacks. The Dart function takes one parameter, so the extra arguments are dropped. Themapcallback declares two and gets the element and the index. toJScreates a new JavaScript function each time. To remove an event listener later, keep the result in a variable and pass that same value toremoveEventListener.toJSCaptureThis(Dart 3.6) passes JavaScript'sthisas the first argument, for APIs that call callbacks as methods.
JSFunction has an optional type argument that documents the signature, as in applyTwice above. It's checked statically: passing ((String s) => 1).toJS to applyTwice fails with The argument type 'JSExportedDartFunction<int Function(String)>' can't be assigned to the parameter type 'JSFunction<int Function(int)>'. At runtime it isn't checked, since JavaScript can call the function with anything.
Promises and futures
JSPromise<T>.toDart turns a promise into a Future<T>. A rejected promise becomes an exception you can catch. Future<T>.toJS turns a future of a JS type into a promise, for Dart code that JavaScript awaits:
import 'dart:js_interop';
extension type User._(JSObject _) implements JSObject {
external int get id;
external String get name;
}
@JS()
external JSPromise<User> loadUser(int id);
@JS()
external JSPromise<JSString> callGreeting(String name);
// A setter for a global: lets Dart store a function where JS can find it.
@JS()
external set fetchGreeting(
JSFunction<JSPromise<JSString> Function(JSString)> f,
);
Future<String> greet(String name) async {
await Future.delayed(const Duration(milliseconds: 5));
return 'Hello, $name!';
}
Future<void> main() async {
// JS promise -> Dart future
final user = await loadUser(7).toDart;
print('${user.id}: ${user.name}');
try {
await loadUser(-1).toDart;
} catch (e) {
print('caught: $e');
}
// Dart future -> JS promise
fetchGreeting = ((JSString name) {
final Future<JSString> f = greet(name.toDart).then((s) => s.toJS);
return f.toJS;
}).toJS;
print((await callGreeting('Ann').toDart).toDart);
}
Output:
7: user7
caught: Error: bad id -1
JS got: Hello, Ann!
A Dart async closure can't be converted directly, because Future<JSString> isn't a JS type:
Error: Function converted via 'toJS' contains invalid types in its function signature: '*Future<JSString>* Function(JSString)'.
Return future.toJS from a regular closure instead, as in the example. To load an ES module at runtime, use importModule('./module.js'.toJS).toDart, which wraps JavaScript's import(). For more on futures see Async and await.
Type checks: use isA, not is
A JavaScript function declared to return JSAny? can return anything. Check what you got with isA<T>() (Dart 3.4). It uses typeof for primitives and instanceof for classes, so it checks the actual JavaScript value:
import 'dart:js_interop';
import 'dart:js_interop_unsafe';
@JS('JSON.parse')
external JSAny? parse(String json);
@JS('Map')
extension type JSMap._(JSObject _) implements JSObject {
external JSMap();
external void set(JSAny key, JSAny? value);
external JSIterable<JSString> keys();
}
String describe(JSAny? v) {
if (v == null) return 'null or undefined';
if (v.isA<JSString>()) return 'string "${(v as JSString).toDart}"';
if (v.isA<JSNumber>()) return 'number ${(v as JSNumber).toDartDouble}';
if (v.isA<JSBoolean>()) return 'boolean ${(v as JSBoolean).toDart}';
if (v.isA<JSArray>()) return 'array of ${(v as JSArray).length}';
if (v.isA<JSMap>()) return 'Map';
if (v.isA<JSObject>()) return 'object';
return 'something else';
}
void main() {
final data = parse('[1, "two", true, null, [5, 6], {"a": 1}]') as JSArray;
for (final item in data.toDart) {
print(describe(item));
}
final m = JSMap()..set('x'.toJS, 1.toJS)..set('y'.toJS, 2.toJS);
print(describe(m));
print(m.keys().toDartIterable.map((k) => k.toDart).toList());
print(globalContext.has('Map'));
}
Output:
number 1
string "two"
boolean true
null or undefined
array of 2
object
Map
[x, y]
true
For a user-defined type like JSMap, isA uses the extension type's JavaScript name (here the @JS('Map') rename) in an instanceof check. JSIterable and toDartIterable (Dart 3.12) let you loop over any JavaScript iterable, such as Map.keys(), from Dart.
Don't use is and as to check JS types. Extension types are erased at runtime, and the JS types are represented differently by each compiler:
import 'dart:js_interop';
extension type URL._(JSObject _) implements JSObject {
external URL(String url);
}
extension type Counter._(JSObject _) implements JSObject {}
void main() {
final JSObject obj = URL('https://dart.dev');
print(obj is Counter); // compares erased types: JSObject vs JSObject
print(obj.isA<Counter>()); // obj instanceof Counter
print(obj.isA<URL>()); // obj instanceof URL
}
Run with dart2js:
true
false
true
obj is Counter is true even though obj is a URL, because both types erase to JSObject. Even is checks on the built-in types are inconsistent: JSON.parse('{}') is JSArray is false with dart2js but true with dart2wasm. The invalid_runtime_check_with_js_interop_types lint catches these. Enable it in analysis_options.yaml:
linter:
rules:
- invalid_runtime_check_with_js_interop_types
dart analyze then reports:
info - isbad2.dart:11:9 - Runtime check between 'JSObject' and 'Counter' involves a runtime check between a JS interop value and an unrelated JS interop type that will always be true and won't check the underlying type. Try using a JS interop member like 'isA' from 'dart:js_interop' to check the underlying type of JS interop values, or make the JS interop type a supertype using 'implements'. - invalid_runtime_check_with_js_interop_types
A cast like v as JSString after an isA check is fine: it tells the type system what you already checked.
Exposing Dart objects to JavaScript
To hand a Dart object to JavaScript code, annotate the class with @JSExport and wrap an instance with createJSInteropWrapper. The wrapper is a JavaScript object with one property per instance member. Calls on it run the Dart code on the original object:
// report.js: JavaScript code that uses an object given to it by Dart
globalThis.runReport = (store) => {
store.add("apples", 3);
store.add("pears", 5);
console.log(`JS sees total = ${store.total}, items = ${store.describe()}`);
store.reset();
};
import 'dart:js_interop';
import 'dart:js_interop_unsafe';
@JSExport()
class Store {
final _items = <String, int>{};
void add(String name, int count) => _items[name] = count;
int get total => _items.values.fold(0, (a, b) => a + b);
@JSExport('describe')
String summary() => _items.keys.join('+');
void reset() {
print('Dart: reset called');
_items.clear();
}
}
@JS()
external void runReport(JSObject store);
void main() {
final store = Store();
runReport(createJSInteropWrapper(store));
print('Dart sees total = ${store.total}');
// Export a plain function as a global.
globalContext['dartVersion'] = (() => '3.13'.toJS).toJS;
}
Run with node -r ./preamble.js -r ./report.js out/exporting.js:
JS sees total = 8, items = apples+pears
Dart: reset called
Dart sees total = 0
@JSExport('describe') renames a member in the wrapper. Private members like _items aren't exported. To expose a single function, convert it with .toJS and store it in a global, either with an external setter (as in the promises example) or with globalContext['name'] = f.toJS from dart:js_interop_unsafe.
DOM programming with package:web
dart:html, dart:svg and the other old browser libraries don't work with dart2wasm and are deprecated ('dart:html' is deprecated and shouldn't be used. Use package:web and dart:js_interop instead.). Their replacement is package:web, a set of interop declarations generated from the Web IDL specs. It's built on dart:js_interop, so it works with both compilers. Names follow the JavaScript APIs: HTMLInputElement, document.querySelector, addEventListener.
<!DOCTYPE html>
<html>
<head>
<title>Todo</title>
<script defer src="main.dart.js"></script>
</head>
<body>
<input id="new-todo" value="Buy milk">
<button id="add">Add</button>
<ul id="todos"></ul>
</body>
</html>
import 'dart:js_interop';
import 'package:web/web.dart';
void main() {
final input = document.querySelector('#new-todo') as HTMLInputElement;
final button = document.querySelector('#add') as HTMLButtonElement;
final list = document.getElementById('todos') as HTMLUListElement;
void addTodo() {
final text = input.value.trim();
if (text.isEmpty) return;
final li = HTMLLIElement()
..textContent = text
..className = 'todo';
list.append(li);
input.value = '';
}
// Event listeners take a JS function.
button.addEventListener('click', ((Event _) => addTodo()).toJS);
// Or use the typed event streams from package:web.
input.onKeyDown.listen((KeyboardEvent e) {
if (e.key == 'Enter') addTodo();
});
button.click(); // simulate a click
input.value = 'Walk the dog';
input.dispatchEvent(KeyboardEvent('keydown', KeyboardEventInit(key: 'Enter')));
document.title = 'Todo (${list.children.length})';
console.log('items: ${list.children.length}'.toJS);
}
Build it and run it in a headless browser that prints the final DOM:
$ dart compile js -O2 -o web/main.dart.js web/main.dart
$ msedge --headless --dump-dom file:///path/to/web/index.html
<!DOCTYPE html>
<html><head>
<title>Todo (2)</title>
<script defer="" src="main.dart.js"></script>
</head>
<body>
<input id="new-todo" value="Buy milk">
<button id="add">Add</button>
<ul id="todos"><li class="todo">Buy milk</li><li class="todo">Walk the dog</li></ul>
</body></html>
The console shows items: 2. Differences from dart:html that you'll notice when migrating:
- elements are created with constructors such as
HTMLLIElement()or withdocument.createElement('li'), not withLIElement()orElement.tag('li') querySelectorreturnsElement?, so you cast to the specific typechildrenis anHTMLCollection, not a DartList: use.lengthand.item(i)- event listeners take a
JSFunction(convert with.toJS), or you use theonClick/onKeyDownstreams thatpackage:webadds throughElementEventGetters - dictionaries like
KeyboardEventInitare object literal types, created with named arguments
dart fix doesn't migrate dart:html code automatically. Most changes are renames, and the package:web migration guide lists them.
Migrating from package:js and dart:js_util
Old (package:js, dart:js_util) |
New (dart:js_interop) |
|---|---|
@JS() library x; + import 'package:js/js.dart' |
import 'dart:js_interop' |
@JS() class Foo { external Foo(); } |
extension type Foo._(JSObject _) implements JSObject { external Foo(); } |
@JS() @anonymous class Options |
extension type with external factory Options({...}) |
@staticInterop classes + extensions |
extension types |
allowInterop(f) |
f.toJS |
js_util.promiseToFuture(p) |
p.toDart |
js_util.getProperty(o, 'x') |
typed external getter, or o['x'] from dart:js_interop_unsafe |
js_util.callMethod(o, 'f', [a]) |
typed external method, or o.callMethod('f'.toJS, a) |
js_util.globalThis |
globalContext |
js_util.jsify(m) / dartify(v) |
m.jsify() / v.dartify() |
o is Foo / instanceof helpers |
o.isA<Foo>() |
dart:html |
package:web |
The main shift is that package:js let you pass Dart lists, maps and functions to JavaScript and converted them behind your back (or not at all, depending on the compiler). dart:js_interop makes every conversion visible in your code.
dart:js_util and package:js are deprecated (dart analyze reports 'dart:js_util' is deprecated and shouldn't be used. Use dart:js_interop instead.). dart2js still compiles them, but dart2wasm doesn't: it dropped dart:js_util in Dart 3.10, and package:js stopped compiling with dart2wasm in 3.11:
$ dart compile wasm -o out/old.wasm bin/old.dart
bin/old.dart:1:8: Error: Dart library 'dart:js_util' is not available on this platform.
import 'dart:js_util' as js_util;
^
The same code under WebAssembly
Code that uses only dart:js_interop and package:web also compiles to WebAssembly. dart compile wasm produces a .wasm module plus an .mjs loader:
$ dart compile wasm -o out/classes.wasm bin/classes.dart
Generated wasm module 'out/classes.wasm', and JS init file 'out/classes.mjs'.
Loaded in Node 24 with the loader's compile and instantiate functions, classes.wasm printed exactly the same output as the dart2js build. As shown above, number printing and is checks on JS types can differ, which is why toDartInt, isA and the lint matter. Compiling and serving Wasm builds is a topic of its own.
Summary
- Declare JavaScript functions and globals as
@JS()externaltop-level members. Use@JS('a.b')for dotted paths and@JS('ns') library;for namespaces. - Wrap JavaScript classes in
extension type X._(JSObject _) implements JSObjectwithexternalconstructors, statics and members. - An
external factorywith only named parameters creates an object literal. - Convert values explicitly:
.toJS/.toDart,toDartInt,jsify()/dartify(),future.toJS,promise.toDart,dartFunction.toJS. - Check JS values with
isA<T>(), neveris, and enableinvalid_runtime_check_with_js_interop_types. - Expose Dart objects with
@JSExportandcreateJSInteropWrapper. - Use
package:webinstead ofdart:html, anddart:js_interopinstead ofpackage:js/dart:js_utilto keep the code working with dart2wasm.