Flutter加载H5与js交互

3. webview_flutter(Null safety)

Flutter加载H5与js交互_第1张图片

(1)描述:嵌入H5页面及与js交互

(2)适合平台:ANDRIOD、IOS

(3)使用

a. 判断页面是否加载完
import 'dart:io';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_base_framework/flutter_base_framework.dart';

import 'package:webview_flutter/webview_flutter.dart';

class TestWebPage extends StatefulWidget {
  @override
  TestWebPageState createState() => TestWebPageState();
}

class TestWebPageState extends State {

  WebViewController _controller;
  bool isLoading = true;  // 设置加载状态

  @override
  void initState() {
    super.initState();
    // Enable hybrid composition.
    if (Platform.isAndroid) WebView.platform = SurfaceAndroidWebView();
  }

  @override
  Widget build(BuildContext context) {
    return AnnotatedRegion(
        value: SystemUiOverlayStyle.dark,
        child: Scaffold(
            body: Container(
                width: double.infinity,
                height: double.infinity,
                child: Stack(
                  children: [
                    Padding(
                      padding: EdgeInsets.only(top: MediaQuery.of(context).padding.top),
                      child: WebView(
                        initialUrl: '需要加载的H5页面',
                        javascriptMode: JavascriptMode.unrestricted,
                        onWebViewCreated: (WebViewController webViewController) {
                          _controller = webViewController;
                        },
                        navigationDelegate: (NavigationRequest request) {
                          setState(() {
                            isLoading = true; // 开始访问页面,更新状态
                          });

                          return NavigationDecision.navigate;
                        },
                        onPageFinished: (String url) {
                          setState(() {
                            isLoading = false; // 页面加载完成,更新状态
                          });
                        }
                      ),
                    ),
                    isLoading /// 根据加载状态来展示页面
                      ? Container(
                        child: Center(
                          child: CircularProgressIndicator(),
                        ),
                      )
                      : Container(),
                  ],
                )
            )
        )
    );
  }
}
b. Flutter调用JS方法

js部分

function fromFlutterMessage (message){
  document.getElementById ("fromFlutter").innerHTML = message;
  return true;
}

Flutter部分

/// 这里的_controller和上边是连起来的

_controller.evaluateJavascript("fromFlutterMessage('这里是来自Flutter的信息')").then((value) => print("发送成功"));
c. JS调用Flutter方法

Flutter部分

///这个是WebView的属性,所以要和WebView结合

javascriptChannels: [
  JavascriptChannel(
    name: "fromJavaScriptMessage",
    onMessageReceived: (JavascriptMessage message) {
      print(message.message);
    }
  ),
].toSet(),

js部分

function sendMessage (message) {
  fromJavaScriptMessage.postMessage(message); /// 这里是关键,方法名要相同
  document.getElementById ("toFlutter").innerHTML = message;
}

(4) 完整代码

HTML部分

DOCTYPE html>
<html lang="en">
  <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>html demotitle>
  head>
  <body>
    <div id="fromFlutter"><span>Flutter发送过来的消息是: span>div>
    <div id="toFlutter"><span>我发送给Flutter的消息是:span>div>
    <button onclick="sendMessage('这里是来自JavaScript的方法')">sendMessageToFlutterbutton>
  body>
  <script>
    <!-- 这个方法是用来给Flutter调用的(即:Flutter调用js方法)-->
      function fromFlutterMessage (message){
      document.getElementById ("fromFlutter").innerHTML = message;
      return true;
    }

    <!-- 这个方法是用来发送一个消息给Flutter的(即:js调用Flutter方法)-->
      function sendMessage (message ) {
      MessageDeal.postMessage(message);
      document.getElementById ("toFlutter").innerHTML = message;
    }
  script>
html>

Flutter部分

/// 在a部分的基础上加了接收js方法的参数,可直接覆盖上边WebView组件

WebView(
  initialUrl: '需要加载的H5页面',
  javascriptMode: JavascriptMode.unrestricted,
  onWebViewCreated: (WebViewController webViewController) {
    _controller = webViewController;
  },
  navigationDelegate: (NavigationRequest request) {
    setState(() {
      isLoading = true; // 开始访问页面,更新状态
    });

    return NavigationDecision.navigate;
  },
  onPageFinished: (String url) {
    setState(() {
      isLoading = false; // 页面加载完成,更新状态
    });
    Future.delayed(Duration(seconds: 1), (){
      _controller.evaluateJavascript("showMessage('你好呀')").then((value) => print("发送成功"));
    });
  },
  javascriptChannels: [
    JavascriptChannel(
      name: "MessageDeal",
      onMessageReceived: (JavascriptMessage message) {
        print(message.message);
      }
    ),
  ].toSet(),
)

你可能感兴趣的:(#,Flutter插件,ios,html)