I build a flutter project and want to call js function from dart and get arguments.
It seems not very difficult but all I have tried not working.
Please help me.
main.dart
import 'dart:js';
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: ElevatedButton(onPressed: (){
callJavaScript();
}, child: const Text('Hello')),
);
}
void callJavaScript() {
context.callMethod('greet', ['John']);
}
}
test.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Call JavaScript function from Dart</title>
<script>
function greet(name) {
console.log("Hello, " + name + "!");
}
</script>
</head>
<body>
<h1>Call JavaScript function from Dart</h1>
<button onclick="greet('World')">Click me!</button>
</body>
</html>
My project structure