解决webview_flutter加载富文本样式不显示问题

353 阅读1分钟

第一步:添加依赖

# WebView插件 https://github.com/flutter/packages/tree/main/packages/webview_flutter
webview_flutter: 4.2.0

第二步:使用方法

WebViewWidget(
    controller: WebViewController()
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..loadHtmlString(HtmlUtils.getHtmlData(newDetailsEntity.content.toString(), 14)))

第三步:添加样式文件,代码如下

class HtmlUtils {
  static String getHtmlData(String bodyHTML, int size) {
    String head =
        "<head><meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no"> <style>img{max-width: 100%; width:100%; height:auto;}body{word-wrap:break-word;margin:0px;font-size:${size}px;}</style></head>";
    return "<html>$head<body>$bodyHTML</body></html>";
  }

  static String getHtmlDataAndColor(String bodyHTML, String color) {
    String head =
        "<head><meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no"><style>img{max-width: 100%; width:100%; height:auto;}*{word-wrap:break-word;margin:0px;padding: 10px 8px 8px 8px;color:$color!important;}</style></head>";
    return "<html>$head<body>$bodyHTML</body></html>";
  }

  static String getHtmlDataSizeAndColor(
      String bodyHTML, int size, String color) {
    String head =
        "<head><meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no"><style>img{max-width: 100%; width:100%; height:auto;}body{word-wrap:break-word;margin:0px;font-size:${size}px;color:}</style></head>";
    return "<html>$head<body>$bodyHTML</body></html>";
  }
}

*注意:WebViewWidget在Column中时,需要添加一个具有高度的控件,否则会提示错误。比如以下写法就可以正常显示

Column(
  crossAxisAlignment: CrossAxisAlignment.start,
  children: [
    Expanded(
      child: WebViewWidget(
          controller: WebViewController()
            ..setJavaScriptMode(JavaScriptMode.unrestricted)
            ..loadHtmlString(HtmlUtils.getHtmlData(newDetailsEntity.content.toString(), 14))),
    )
  ],
)