webview_flutter的动态高度计算

如题,webview_flutter的动态高度计算,解决方案有二种。

解决方案1,掘金这篇文章讲明白了,计算准确,方案是:js和flutter通信,看这位大神的就行了。
地址如下:

https://juejin.cn/post/7056353175900520462

下面的是我自己写的demo,可看可不看

顶部声明变量
//WebView 需要的变量属性如下,缺一不可
 double _webViewHeight = 0;
  String _htmlString = "";
  final String _html1 = """
    <!DOCTYPE html>
        <html>
         <meta content="width=device-width,initial-scale=1.0, maximum-scale=0.5, user-scalable=0" name="viewport"/>
         <meta name="apple-mobile-web-app-capable" content="no" />
         <meta name="format-detection" content="telephone=no,email=no,adress=no"/>
         <body>
  """;
  final String _html2 = """
      </body>
      <script type="text/javascript">
        const resizeObserver = new ResizeObserver(entries =>
        flutterMessage.postMessage(document.body.scrollHeight.toString()));
        resizeObserver.observe(document.body);
      </script>
    </html>
  """;
网络数据拿到html富文本代码
_htmlString = "网络请求回来的html代码";
///商品详情页里的 富文本,使用webview进行加载
  Widget _buildGoodsDescribeImgView(){
    if(_detailsModel!.bewrite.isNotEmpty){
      _htmlString = _html1 + _detailsModel!.bewrite + _html2;
      return SizedBox(
        width: WYSizeFit.screenWidth,
        height: _webViewHeight,
        child: WebView(
          javascriptMode: JavascriptMode.unrestricted,
          onWebViewCreated: (WebViewController controller) {
            //如果加载的是html情况
            controller.loadHtmlString(_htmlString);
          },
          onPageFinished: (url) async {
          },
            //JavascriptChannel来进行交互
          javascriptChannels: <JavascriptChannel>{
            //参数为Set,可以传入多个JavascriptChannel,根据name作为哈希值
            JavascriptChannel(
            name: 'flutterMessage',
            onMessageReceived: (JavascriptMessage message) {
              _webViewHeight = double.parse(message.message) * 0.5;
              _webViewHeight += 20;
              setState(() {
              });
            },
          ),
          },
        ),
      );
    }
    return const SizedBox(width: 0,height: 0,);
  }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容