Using JavaScript with Flutter Web

Flutter Web enables the development of progressive web apps (PWAs) using Dart. However, to access browser APIs or integrate with existing JavaScript code, you’ll need to interoperate between Dart and JavaScript. Below, we explore how to achieve this in a Flutter web app.

Interoperating JavaScript with Dart

Dart.js is a built-in library that facilitates communication between Dart and JavaScript.

Adding JavaScript Functions

  1. Create a JavaScript file (app.js) in the web directory.
  2. Define functions or variables on the window object.
function alertMessage(text) {
    alert(text);
}

window.logger = (flutter_value) => {
   console.log({ js_context: this, flutter_value });
}
  1. Include the JavaScript file in the HTML document’s head using a <script> tag with the defer attribute to ensure it loads after the HTML body.
<head>
    <script src="app.js" defer></script>
</head>

Calling JavaScript Functions from Dart

  1. Import the dart:js library in your Dart code.
  2. Use the callMethod method to invoke JavaScript functions.
import 'dart:js' as js;

js.context.callMethod('alertMessage', ['Flutter is calling JavaScript!']);

You can pass arguments from Dart to JavaScript functions using the second parameter of callMethod.

js.context.callMethod('logger', [_someFlutterState]);

Accessing JavaScript Objects in Dart

If you have data in JavaScript that you need to access in Dart, you can convert JSON-serializable JavaScript objects for use in Dart.

  1. Define a JavaScript object.
window.state = {
    hello: 'world'
}
  1. Convert the JavaScript object to a Dart object using JsObject.fromBrowserObject.
import 'dart:js' as js;

var state = js.JsObject.fromBrowserObject(js.context['state']);
print(state['hello']); // Output: world

This way, you can seamlessly integrate JavaScript functionality and data with your Flutter web application.

Comments

Load Comments