您将需要在您的 html 周围添加一个额外的内容并使用 javascript 事件处理程序。
我们将对其进行一点自定义,而不是将原始 html 传递给 webview。
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();
如何使用 Webview :
/// 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
解释 :
当 div 内容发生变化时,将发送一个具有新大小的事件。Flutter InAppWebView 会监听它并调用回调。我们只需要用当前视图高度更新 WebView 的父容器。就是这样,webview 像一个小部件一样显示在颤动中,没有任何大小问题。