A working example demonstrating how to embed a Flutter web application into an existing HTML page and enable bidirectional communication between JavaScript and Flutter using modern dart:js_interop.
This project showcases:
- Embedding Flutter web apps into existing HTML pages
- JavaScript → Flutter communication using
postMessageAPI - Flutter → JavaScript communication using
@JS()annotations - Async JavaScript calls from Flutter (Promises, async/await)
- JSON data exchange between JavaScript and Flutter
The example includes several JavaScript functions that can be called from Flutter:
showAlert(message)- Display browser alert dialogsgetData()- Return simple string datagetJsonData()- Return JSON-encoded datagetAsyncData()- Return Promise-based async string datagetAsyncJsonData()- Fetch and return JSON from a local file
The Flutter app listens for messages from the host page using the window.onmessage API, demonstrating how to receive data from JavaScript.
- Flutter SDK (^3.10.0)
- A web browser
- Clone this repository:
git clone <your-repo-url>
cd embedded_project- Install dependencies:
flutter pub get- Run the application:
flutter run -d chromeOr build for production:
flutter build weblib/
├── main.dart # Main Flutter app with message listener
└── services/
└── js_interop_service.dart # JavaScript interop service layer
web/
└── index.html # Host HTML page with JS functions
Flutter uses dart:js_interop to call JavaScript functions:
@JS()
external void _showAlert(String message);
void showAlert(String message) {
_showAlert(message);
}The host page sends messages using postMessage:
window.postMessage({
type: 'FROM_JS',
payload: 'Your message here'
}, '*');Flutter listens for these messages:
window.onmessage = (JSAny event) {
final messageEvent = event as JSMessageEvent;
final data = (messageEvent.data.dartify() as Map).cast<String, dynamic>();
// Handle the data
}.toJS;Flutter can await JavaScript Promises:
Future<String> getAsyncData() async {
final promiseResult = await _getAsyncData().toDart;
return (promiseResult as JSString).toDart;
}dart:js_interop- Modern Flutter web JavaScript interop (replaces deprecateddart:js)JSPromise- For handling JavaScript async operationspostMessageAPI - For JavaScript → Flutter messaging- Extension types - Type-safe JavaScript object access
This project was created by adapting deprecated JavaScript interop code to work with modern Flutter web standards. It serves as a reference for developers needing bidirectional communication between Flutter web apps and their host pages.
MIT License - See LICENSE file for details.
Contributions, issues, and feature requests are welcome! Feel free to check the issues page or submit a pull request.