我想告诉你如何从flutter WebView向JS发送消息:
- 在 JS 代码中,您需要将需要触发的函数绑定到窗口
const function = () => alert('hello from JS');
window.function = function;
- 在 WebView 小部件实现的代码中,您需要像这样声明 onWebViewCreated 方法
WebView(
onWebViewCreated: (WebViewController controller) {},
initialUrl: 'https://url.com',
javascriptMode: JavascriptMode.unrestricted,
)
- 在类小部件中声明
var _webViewController;
class App extends State<MyApp> {
final _webViewController;
}
- 在onWebViewCreated写下这段代码
onWebViewCreated: (WebViewController controller) {
_webViewController = controller;
},
然后你可以像这样运行代码:
class App extends StatelessWidget {
var _webViewController;
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
home: Scaffold(
body: WebView(
onWebViewCreated: (WebViewController controller) {
_webViewController = controller;
},
initialUrl: 'https://url.com',
javascriptMode: JavascriptMode.unrestricted,
),
floatingActionButton: FloatingActionButton(
onPressed: () {
// When you click at this button youll run js code and youll see alert
_webViewController
.evaluateJavascript('window.function ()');
},
child: Icon(Icons.add),
backgroundColor: Colors.green,
),
),
);
}
}
但是如果我们想将这个 _webViewController 实例共享给抽屉等其他小部件怎么办?
在这种情况下,我决定实现 Singleton pattern 并将 _webViewController 实例存储在其中。
所以
单例类
class Singleton {
WebViewController webViewController;
static final Singleton _singleton = new Singleton._internal();
static Singleton get instance => _singleton;
factory Singleton(WebViewController webViewController) {
_singleton.webViewController = webViewController;
return _singleton;
}
Singleton._internal();
}
然后
onWebViewCreated: (WebViewController controller) {
var singleton = new Singleton(controller);
},
最后在我们的抽屉小部件中,即(在这里你可以使用任何你想要的小部件)
class EndDrawer extends StatelessWidget {
final singleton = Singleton.instance;
@override
Widget build(BuildContext context) {
return Drawer(
child: Column(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
SizedBox(
width: 200,
child: FlatButton(
onPressed: () {
singleton.webViewController.evaluateJavascript('window.function()');
Navigator.pop(context); // exit drawer
},
child: Row(
children: <Widget>[
Icon(
Icons.exit_to_app,
color: Colors.redAccent,
),
SizedBox(
width: 30,
),
Text(
'Exit',
style: TextStyle(color: Colors.blueAccent, fontSize: 20),
),
],
),
)),
],
),
);
}
}
如果你想从 JS 代码接收消息到你的 Flutter App 你需要:
- 在您的 js 代码中
window.CHANNEL_NAME.postMessage('Hello from JS');
- 在您的颤振代码中。
当您运行 JavascriptChannel(name: 'CHANNEL_NAME', ...)
使用您在构造函数中编写的名称(在本例中为 CHANNEL_NAME)
因此,当我们致电 window.CHANNEL_NAME.postMessage('Hello from JS'); 时,我们会收到一条我们发送的消息
WebView(
javascriptChannels: [
JavascriptChannel(name: 'CHANNEL_NAME', onMessageReceived: (message) {
print(message.message);
})
].toSet(),
initialUrl: 'https://url.com',
)
所以我们到了。
我是 Flutter 代码的新手
因此,如果您对此有其他更好的体验,可以在 cmets 中编写以帮助其他人!