• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

Flutter webView加载html富文本

武飞扬头像
不上班行不行
帮助1

WebView 加载 Html 字符串

1.添加依赖

在项目的 pubspec.yaml 文件中添加 webview_flutter 插件的依赖:

dependencies:
webview_flutter: ^3.0.0

2.引入webView

在需要加载的页面引入webView头文件

import 'package:webview_flutter/webview_flutter.dart';

3.加载富文本

在需要加载的页面引入webView头文件

WebView(
        javascriptMode: JavascriptMode.unrestricted,
        onWebViewCreated: (WebViewController controller){
          if(htmlStr.isNotEmpty){
            controller.loadHtmlString(htmlStr);
          }
        },
      ),

4.富文本适配

富文本如果没有头部的话,会出现字体过小,宽高不适应手机屏幕的现象。需要加入额外的样式修饰

String htmlStr = """<html>
                <head>
                <meta charset='UTF-8'>
                <title>
                ${data.title}
                </title>
                <style type=text/css> 
                body {font-size:20px; line-height:40px;background-color: transparent;}
                p {font-size:30px; line-height:40px;background-color: transparent;}
                div {font-size:25px; line-height:40px;background-color: transparent;text-align:center;color:#333333;}
                </style>
                </head>
                <body 
                style='padding-left: 15px;padding-right: 15px;padding-top: 15px;'>
                <div style='color:#FF0000;font-size:40px; line-height:80px;background-color: transparent;text-align:center;font-weight: bold;'>
                ${data.title}<div>
                <div>来源:${data.publishName} 发布时间:${data.publishTime}<div>
                ${data.content}
                </body> 
                </html>""";
学新通

除此之外,loadHtmlString 还有一个可选参数 baseUrl ,作用是当 html 字符串中使用到了相对路径的 url 时,设置了 baseUrl 后 WebView 加载 html 请求相应 url 时就会带上 baseUrl,如 html 字符串中有显示图片,图片地址写的是相对路径,此时就可以使用 baseUrl 参数来解决,如下

WebView(
  javascriptMode: JavascriptMode.unrestricted,
  onWebViewCreated: (WebViewController controller){
    controller.loadHtmlString(htmlStr, baseUrl: baseUrl);
  },
)

5.WebView 高度自适应

WebView 默认无法做到高度自适应,即根据 html 内容高度自适应,当在 Column 等控件中使用 WebView 而不手动设置固定高度时则会报错。
如果要做到高度自适应,则需要用到 js 方法,在 html 中通过 js 监听页面大小的变化,然后获取页面高度再将高度传递到 Flutter 中,在 Flutter 中获取到高度后再动态改变 WebView 的高度。
实现步骤如下:

给 WebView 添加一个 JavascriptChannel 用于 js 与 Flutter 通信
在 html 中添加 script 使用 ResizeObserver 监听 body 元素的大小变化,在变化回调里调用上一步添加的 JavascriptChannel 发送页面高度的消息
在 Flutter 中接收到消息时,获取 js 发送过来的高度值,然后更新 WebView 的高度
代码如下:

String html = """
   <!DOCTYPE html>
        <html>
        <head><meta name="viewport" content="width=device-width, initial-scale=1.0"></head>
          <body>
            <p> Hello WebView</p>
            <img src="https://image.百度.com/search/detail?z=0&word=宠物图片&hs=0&pn=0&spn=0&di=&pi=227259&tn=百度imagedetail&is=&ie=utf-8&oe=utf-8&cs=4162611394,4275913936&os=&simid=&adpicid=0&lpn=0&fr=albumsdetail&fm=&ic=0&sme=&cg=&bdtype=&oriquery=&objurl=https://t7.百度.com/it/u=4162611394,4275913936&fm=193&f=GIF&fromurl=ipprf_z2C$qAzdH3FAzdH3Fooo_z&e3Bejj6_z&e3Bv54AzdH3Fri5p5AzdH3Fnan0m9c8n?7p4_f576vj=kwt17&7p4_4j1t74=t4w2jfjw6vi&vit1=lad&gsm=0&islist=&querylist=&album_tab=动物&album_id=688"/>
          </body>
        </html>
        <script>
          const resizeObserver = new ResizeObserver(entries =>
          Resize.postMessage(document.documentElement.scrollHeight.toString()) )
          resizeObserver.observe(document.body)
        </script>
  """;

SizedBox(
  height: webViewHeight,
  child: WebView(
    javascriptMode: JavascriptMode.unrestricted,
    onWebViewCreated: (WebViewController controller){
      controller.loadHtmlString(html, baseUrl:bsaeUrl);
    },
    javascriptChannels: {
      JavascriptChannel(name: "Resize", onMessageReceived: (JavascriptMessage message) {
        double height = double.parse(message.message);
        setState(() {
          webViewHeight = height;
        });
      })
    }
  ),
)
学新通

如上,给 WebView 外面包了一层 SizeBox 用于限制 WebView 的高度,同时给 WebView 添加了名为 Resize 的 JavascriptChannel , 在 html 字符串中添加了 script 使用 js 的 ResizeObserver 监听页面元素大小变化,在变化回调里获取元素的 scrollHeight 值并将其发送到 Flutter,在 Flutter 的 JavascriptChannel 消息回调里获取高度值并更新 SizeBox 的高度。从而实现了 WebView 的高度自适应。

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhfkkfhj
系列文章
更多 icon
同类精品
更多 icon
继续加载