D
Flutter WebHard50 XP4 min read

How do you call JavaScript from Flutter Web (JS interop)?

TL;DR: Use the package:js (legacy) or dart:js_interop (Dart 3 + WASM) to call JavaScript libraries from Dart. Annotate external functions with @JS() and bind them to Dart signatures. For simple calls, use js.context.callMethod().

Full Answer

Sometimes you need to use a JavaScript library (analytics, maps, payments) that has no Flutter package. JS interop lets Dart call JavaScript APIs directly.

Two APIs

  • package:js (@JS annotations): legacy, works with CanvasKit/HTML renderer
  • dart:js_interop (@JS + extension types): Dart 3.3+, WASM-compatible, the future
  • dart:js (low-level): js.context['functionName'] for quick calls
⚠️

dart:js_interop extension types are the correct approach for new code targeting Dart 3 + WASM. The old package:js will not work with WASM compilation.

Code Examples

dartdart:js_interop for analytics
Output
// Calls JavaScript gtag() from Dart
// .toJS and .toDart convert between Dart and JS types

Common Mistakes

  • Using package:js for WASM targets — use dart:js_interop instead
  • Passing Dart Maps directly to JS — must convert with .jsify() or explicit JSObject construction

Interview Tip

💡

The .toJS / .toDart conversion API in dart:js_interop shows Dart's careful type boundary. Explain that WASM and JS don't share memory — every value must be explicitly converted.

#js-interop#dart-js#package-js#wasm-interop