1

In flutter, when using Webview, you sometimes want to display contents above and under it.

Problem - 1 ? Webview need constraints else it couldn't be displayed : you need to wrap the Webview under a container with a fixed size or under a column with an expandable or somethings like that.

Problem - 2 ? Height could be easily fetched but sometimes Webview load asynchronous data like embed script which will change the style of the page. In this situation it's hard to known how and when fetch the Webview height.

With these problem, most of the times your Webview will display a scroll bar and when reached the bottom of the webview user will have trouble to scroll your flutter page. The scroll will conflict with the Webview.

What is the best way to fix that ?

3 Answers 3

10

You will need to add an extra around your html and use javascript event handler.

Instead of passing the raw html to the webview we will custom it a little bit.

final htmlFromApi = await getContent();
final html = Uri.dataFromString('''
                        <html lang="fr">
                           <meta name="viewport" content="width=device-width user-scalable=no zoom=1.1">
                           <style>img {max-width: 100%; height: auto}</style>
                           <body>
                            <div class="container" id="_flutter_target_do_not_delete">$htmlFromApi</div>
                            <script>
                            function outputsize() {
                                if (typeof window.flutter_inappwebview !== "undefined" && typeof window.flutter_inappwebview.callHandler !== "undefined")
                                   window.flutter_inappwebview.callHandler('newHeight', document.getElementById("_flutter_target_do_not_delete").offsetHeight);
                                }
                              new ResizeObserver(outputsize).observe(_flutter_target_do_not_delete)
                            </script>
                          </body>
                        </html>
                      ''', mimeType: "text/html", encoding: Encoding.getByName("utf-8")).toString();

How to use Webview with that :

/// Define it to 1 else the Webview widget will not start loading.
double height = 1;
///some widgets
Container(
  height: height,
  child: InAppWebView(
    initialOptions: InAppWebViewGroupOptions(
      crossPlatform: InAppWebViewOptions(
        supportZoom: false,
        javaScriptEnabled: true,
        disableHorizontalScroll: true,
        disableVerticalScroll: true,
      ),
    ),
    onWebViewCreated: (InAppWebViewController controller) {
      controller.addJavaScriptHandler(
        handlerName: "newHeight",
        callback: (List<dynamic> arguments) async {
          int? height = arguments.isNotEmpty ? arguments[0] : await controller.getContentHeight();
          if (mounted) setState(() => this.height = height!.toDouble());
        });
    },
    initialUrl: html,
  ),
),
///some widgets

Explanation :

When the div content will change, an event will be send with the new size. The flutter InAppWebView will listen to it and call the callback. We just can update the WebView's parent container with the current view height. And that's all, the webview is displayed like a widget in flutter without any size issue.

9
  • Post edited, I used in addition size from arguments.
    – Eng
    Jul 7, 2021 at 22:16
  • It just gives 1
    – Balaji
    Oct 26, 2022 at 14:29
  • @Balaji Got the same with flutter_webview recently. Issue was about the message inside controller.addJavaScriptHandler which was a double instead of int. Can you check if here it's same ?
    – Eng
    Oct 26, 2022 at 16:11
  • @Balaji can you share your example code it will help me to debug
    – Eng
    Oct 26, 2022 at 16:32
  • Can you check my answer? @Eng
    – Balaji
    Dec 1, 2022 at 9:35
2
      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;
            });
1
  • Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
    – Community Bot
    Nov 9, 2021 at 6:38
0

UPDATE 2022 DECEMBER!!

        ///
      double webViewHeight = 1;

      WebViewController? controller;


      WebView(
        initialUrl: widget.url,
        onWebViewCreated: (WebViewController c) {
          controller = c;
        },
        onPageFinished: (_) {
          updateHeight();
        },
        javascriptMode: JavascriptMode.unrestricted,
      );

     // This calculates the height
     void updateHeight() async {
       double height = double.parse(await 
          controller!.runJavascriptReturningResult('document.documentElement.scrollHeight;'));
       print(height); // prints height
     }

Based on this, I created a widget you can put inside listview or any scrollable area It can automatically detect height and set itself

class DynamicHeightWebView extends StatefulWidget {
  ///
  final String url;

  ///
  const DynamicHeightWebView({Key? key, required this.url}) : super(key: key);

  @override
  State<DynamicHeightWebView> createState() => _DynamicHeightWebViewState();
}

class _DynamicHeightWebViewState extends State<DynamicHeightWebView>
    with AutomaticKeepAliveClientMixin {
  ///
  double webViewHeight = 1;

  WebViewController? controller;

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return SizedBox(
      height: webViewHeight,
      child: WebView(
        initialUrl: widget.url,
        onWebViewCreated: (WebViewController c) {
          controller = c;
        },
        onPageFinished: (_) {
          updateHeight();
        },
        javascriptMode: JavascriptMode.unrestricted,
      ),
    );
  }

  void updateHeight() async {
    double height = double.parse(await controller!.runJavascriptReturningResult(
        'document.documentElement.scrollHeight;'));
    if (webViewHeight != height) {
      setState(() {
        webViewHeight = height;
      });
    }
  }

  @override
  bool get wantKeepAlive => true;
}

You can remove AutomaticKeepAliveClientMixin if you want.

1
  • 1
    This will not work if some js script continue to load after the html page : for example social network embedder.
    – Eng
    Dec 1, 2022 at 16:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.