在flutter项目中嵌入Web项目时可以使用 flutter_inappwebview 插件,此插件包含了多种api,可以较大程度的自定义实现和Web的交互及通讯。以下是使用方法:
InAppWebView.fromPlatformCreationParams(
params: PlatformInAppWebViewWidgetCreationParams(
initialUrlRequest: URLRequest(
url: WebUri(widget.url),
allowsCellularAccess: true,
cachePolicy:
URLRequestCachePolicy.RETURN_CACHE_DATA_ELSE_LOAD),
keepAlive: InAppWebViewKeepAlive(),
onWebViewCreated: (controller) {
baseState.platformWebViewController = controller;
// 添加 JavaScript Handler
baseState.platformWebViewController.addJavaScriptHandler(
handlerName: 'messageFromWebView',
callback: (args) {
receiveMessage(args);
},
);
},
onConsoleMessage: (_, message) {
consoleMessage(message);
},
onLoadStart: (controller, url) {
hideTabBar(url);
},
onUpdateVisitedHistory: (controller, url, isReload) {
hideTabBar(url);
},
onLoadStop: (controller, url) {
setEnv();
},
),
)
上文中的 messageFromWebView 是和web端通讯的通道明称,可自行约定
onConsoleMessage Api可以监听到web项目在控制台打印的一下日志
如果给Web端发送消息时失败可以参考以下代码:
baseState.platformWebViewController.evaluateJavascript(
source: "receiveMessageFromFlutter({name:'SET_ENV'});",
contentWorld: ContentWorld.PAGE
);
contentWorld: ContentWorld.PAGE 为关键属性。