Flutter获取webview的高度

Flutter获取webview的高度,第1张

1、官方插件webview_flutter

核心是在 onPageFinished 方法中 用js获取高度:

var originalHeight = await _webController.runJavascriptReturningResult("document.body.offsetHeight;");

注意:也有人说用这个 

var originalHeight = await _webController!.runJavascriptReturningResult("document.documentElement.clientHeight;");

但是这个我在尝试的时候获取到的永远是你设定的初始值,而不是网页的真实高度,

还有一个js 语句"document.body.scrollHeight",具体结果请自行尝试。

参考:webview_flutter的webview高度计算

webview加载网页获取高度

代码如下:

  double _webHeight = 500;  //去计算得到网页的高度,然后设置高度
  double _webWidth;// 已知屏幕宽度
  double _originalHeight;//原高度

  @override
  void initState() {
    super.initState();
    if (Platform.isAndroid) {
      WebView.platform = SurfaceAndroidWebView();
    }
    _webWidth = ScreenUtil().screenWidth;
    ........
  }

@override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      resizeToAvoidBottomInset: false,
      appBar: AppBar(
        elevation: 0,
        leading: appBarLeading(context),
      ),
      body: EmptyContainer(
        type: _emptyType,
        child: Stack(
                children: [
                  Column(
                    mainAxisSize: MainAxisSize.max,
                    children: [
                      Expanded(
                        child: SmartRefresher(
                          enablePullDown: false,
                          enablePullUp: _commentList.length == 0 ? false : true,
                          footer: appCustomFooter(),
                          controller: _refreshController,
                          onLoading: _loadCommentList,
                          child: CustomScrollView(
                              slivers: [
                                  _renderContent(),// 内容
                                  _renderComment(),// 评论列表
                                  _renderCommentEmpty()// 默认评论展示
                                ]
                          ),
                        ),
                      ),
                      Container(
                        height: 40 + ScreenUtil().statusBarHeight,
                      )
                    ],
                  ),
                  _renderCommenInput() //评论输入框
                ],
              ),
      ),
    );
  }


  _renderContent() {
    return SliverToBoxAdapter(
      child: Container(
        padding: EdgeInsets.only(bottom: 15, top: 5),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Container(
              padding: EdgeInsets.only(left: 10, right: 10),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                      Strings.autoLineString(_model?.title.toString() ?? ""),
                      style: TextFont.columnTextBold(20, ColorTool.hex333),
                      maxLines: 2),
                  Padding(padding: EdgeInsets.only(top: 5)),
                  Text(
                      "文章分类:${_model?.catName ?? ""}     
                      ${_model?.views_num ?? "1"}人浏览",
                      style: TextFont.medium(10, ColorTool.hex333)),
                ],
              ),
            ),
            Padding(padding: EdgeInsets.only(top: 16)),
            // HtmlWidget(_model?.content ?? "",
            //   customWidgetBuilder: (e){
            //     switch(e.localName){
            //       case 'p':
            //         return {
            //           "width":"20"
            //         };
            //     }
            //     return null;
            //   },
            // ),
   Container(
      height: _webHeight,
      width: _webWidth,
      child: WebView(
        // gestureRecognizers: [Factory(() => EagerGestureRecognizer())].toSet(),
                javascriptMode: JavascriptMode.unrestricted,
                onWebViewCreated: (WebViewController webViewController) {
                  _controller.complete(webViewController);
                  _webController = webViewController;
                  _webController.loadUrl(_webUrl);
                },
                javascriptChannels: {
                  // _toasterJavascriptChannel(context),
                },
                onPageStarted: (String url) {
                  print('Page started loading: $url');
                },
                onProgress: (int progress) {
                  print("WebView is loading (progress : $progress%)");
                },
                onPageFinished: (String url) async {
                  //获取webView原始高度
                  var originalHeight = await _webController.runJavascriptReturningResult("document.body.offsetHeight;");
                  _originalHeight = double.parse(originalHeight);
                  setState(() {
                    _webHeight = _originalHeight <= 0 ? 300 : _originalHeight;
                  });
                  print('网页高度-----' + _originalHeight.toString());
                },
                gestureNavigationEnabled: true,
                backgroundColor: const Color(0x00000000),
              ),
            ),
          ],
        ),
      ),
    );
  }

.........................
.........................

2、使用 InAppWebView

  flutter_inappwebview: ^5.3.2

在loadStop中调用


  int contentHeight = await _controller.getContentHeight();
  double zoomScale = await _controller.getZoomScale();
  double htmlHeight = contentHeight.toDouble() * zoomScale;
  double htmlHeightFixed = double.parse(htmlHeight.toStringAsFixed(2));
   if (htmlHeightFixed == 0.0) {
        return;
   }
  setState(() {
        _htmlHeight = htmlHeightFixed + 0.1;
   });

 参考:Flutter and InAppWebView How to get height? - Stack Overflow

 InappWebView 使用方法请自行查找pub例子

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/996864.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-21
下一篇 2022-05-21

发表评论

登录后才能评论

评论列表(0条)

保存