Flutter中嵌入web

在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 为关键属性。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容