CodeBlanks Logo Icon CodeBlanks

JS interop

Learn JavaScript interop with dart:js_interop.

dart:js_interop

dart:js_interop is the library that builds a type-safe bridge between Dart and JavaScript. It is the modern JS interop path arriving with Dart 3. You declare JS functions with the @JS() annotation and the external keyword.

Example: @JS() external void alert(JSString msg);. This makes the browser's alert function callable from Dart. It replaces the old dart:js and package:js APIs; it works with dart2wasm.

Calling a JS function

To call a JS function from Dart you first declare it as external: @JS() external void consoleLog(JSString msg);. This makes a browser function like console.log callable from Dart.

Calling: consoleLog('Hello'.toJS);. Here .toJS converts a Dart String to a JS String. On return you use .toDart. These conversions form the type-safe bridge of dart:js_interop.

Practice Print dart:js_interop info

Add import 'dart:js_interop';. Add a @ JS() annotated external void consoleLog(JSString msg); declaration. In main add print('dart:js_interop: JS bridge') and print('Annotation: @ JS()').

Starter code

main.dart
// import the dart:js_interop package
// add @ JS() external consoleLog declaration

void main() {
  // print dart:js_interop info
}

Sample solution

main.dart
import 'dart:js_interop';

@JS()
external void consoleLog(JSString msg);

void main() {
  print('dart:js_interop: JS bridge');
  print('Annotation: @ JS()');
}

Expected output

dart:js_interop: JS bridge
Annotation: @ JS()

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does dart:js_interop provide?

  • File I/O
  • Browser cookies
  • Network requests
  • Type-safe bridge with JS Correct answer

Explanation: dart:js_interop builds a type-safe bridge between Dart and JS.

2 Match the dart:js_interop parts

Term Meaning
dart:js_interop JS bridge
@ JS() Annotation
external External declaration
toJS Dart → JS

3 The toJS conversion

Question
'Hello'.____;
Answer
'Hello'.toJS;

Explanation: .toJS converts a Dart String to a JS String.

All lessons in Advanced