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
- Create a JavaScript file (
app.js
) in theweb
directory. - Define functions or variables on the
window
object.
function alertMessage(text) {
alert(text);
}
window.logger = (flutter_value) => {
console.log({ js_context: this, flutter_value });
}
- Include the JavaScript file in the HTML document’s head using a
<script>
tag with thedefer
attribute to ensure it loads after the HTML body.
<head>
<script src="app.js" defer></script>
</head>
Calling JavaScript Functions from Dart
- Import the
dart:js
library in your Dart code. - 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.
- Define a JavaScript object.
window.state = {
hello: 'world'
}
- 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.