【Flutter】四十三、webview_flutter的使用

使用webview_flutter可用来加载网页。

一、安装webview_flutter插件

webview_flutter: ^0.3.15+1

二、设置网络权限

2.1 Android设置

【Flutter】四十三、webview_flutter的使用_第1张图片
AndroidManifest.xml中添加一下代码(manifest标签下方添加即可):

<uses-permission android:name="android.permission.INTERNET" />

iOS设置

在ios/Runner/Info.plist中添加:

<key>io.flutter.embedded_views_previewkey>
<string>YESstring>

三、属性说明

WebView({
    Key key,
    this.onWebViewCreated, // 创建webview触发
    this.initialUrl, // 网页初始url
    this.javascriptMode = JavascriptMode.disabled, // JS执行模式(是否允许JS执行)
    this.javascriptChannels, // JS和Flutter通信的Channel;
    this.navigationDelegate, // 路由委托可拦截url
    this.gestureRecognizers, // 手势监听
    this.onPageFinished, // 加载完毕触发
    this.debuggingEnabled = false,
    this.userAgent,
    this.initialMediaPlaybackPolicy =
        AutoMediaPlaybackPolicy.require_user_action_for_all_media_types,
  }) 

js调用Flutter

flutter:
...
javascriptChannels: <JavascriptChannel>[
	// 以下name的值需要和js中postMessage的调用者一致
	JavascriptChannel(name: 'Toast', onMessageReceived: (JavascriptMessage message) {
		print(message.message);
	})
].toSet(),
...
js:
<button onclick="toast()">调用Flutter</button>
function toast() {
      Toast.postMessage('调用Flutter')
}

flutter调用js

  在onWebViewCreated回调函数中会有一个WebViewController类型参数,通过该参数调用evaluateJavascript方法即可调用js。

四、示例

	WebView(
          onWebViewCreated: (WebViewController controller) {
            _controller = controller;
          },
          javascriptChannels: <JavascriptChannel>[
            JavascriptChannel(name: 'Toast', onMessageReceived: (JavascriptMessage message) {
              print(message.message);
            })
          ].toSet(),
          initialUrl: 'http://127.0.0.1:8080/index.html',
          javascriptMode: JavascriptMode.unrestricted,
          navigationDelegate: (NavigationRequest request) {
            if (request.url.startsWith('http://127.0.0.1')) {
              print('http://127.0.0.1被拦截');
              return NavigationDecision.prevent;
            }
            return NavigationDecision.navigate;
          },
          onPageFinished: (str) {
            print(str);
            String js = 'let elem = document.createElement("div");elem.textContent = "添加";document.body.appendChild(elem);';
            _controller.evaluateJavascript(js);
          },
        )

你可能感兴趣的:(【Flutter】学习记录)