flutter开发实战-inappwebview实现flutter与Javascript的交互JSBridge
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
class MyInAppWebViewPage extends StatefulWidget {
@override
_MyInAppWebViewPageState createState() => new _MyInAppWebViewPageState();
}
class _MyInAppWebViewPageState extends State<MyInAppWebViewPage> {
InAppWebViewController webView;
String jsBridgeScript = """
window.flutter_inappwebview_jsbridge = {
callMethod: function(method, successCallback, errorCallback, args) {
flutter_inappwebview.callMethod(method, successCallback, errorCallback, args);
},
subscribeToMethod: function(method, callback) {
flutter_inappwebview.subscribeToMethod(method, callback);
},
subscribeToEvent: function(eventName, callback) {
flutter_inappwebview.subscribeToEvent(eventName, callback);
},
unsubscribeFromMethod: function(subscriptionId) {
flutter_inappwebview.unsubscribeFromMethod(subscriptionId);
},
unsubscribeFromEvent: function(subscriptionId) {
flutter_inappwebview.unsubscribeFromEvent(subscriptionId);
}
};
""";
@override
void initState() {
super.initState();
}
@override
void dispose() {
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("InAppWebView")
),
body: Container(
child: Column(children: <Widget>[
Expanded(
child: InAppWebView(
initialUrlRequest: URLRequest(url: Uri.parse("https://www.example.com")),
initialJavaScript: jsBridgeScript,
onWebViewCreated: (InAppWebViewController controller) {
webView = controller;
},
onLoadStart: (InAppWebViewController controller, String url) {
},
onLoadStop: (InAppWebViewController controller, String url) {
},
),
)
])
)
);
}
}
这个代码实例展示了如何在Flutter应用中使用InAppWebView插件创建一个包含JSBridge的WebView,从而实现Flutter与JavaScript的交互。通过定义jsBridgeScript
变量,我们创建了一个简单的JSBridge,允许Flutter调用JavaScript函数并接收来自Web内容的事件和方法回调。
评论已关闭