获取数据后赋值
final htmlPage =
"""
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
body { margin: 0; padding: 0; font-size: 14px; }
table {
border-collapse: collapse;
width: 100% !important;
max-width: 100% !important;
word-break: break-word;
}
td, th {
border: 1px solid #ddd;
padding: 8px;
}
img {
max-width: 100% !important;
height: auto !important;
}
</style>
</head>
<body>
$goods_desc
</body>
<script>
const observer = new ResizeObserver(() => {
Resize.postMessage(document.body.scrollHeight);
});
observer.observe(document.body);
</script>
</html>
""";
_webViewController = WebViewController()
..setJavaScriptMode(JavaScriptMode.unrestricted)
..addJavaScriptChannel(
'Resize',
onMessageReceived: (message) {
double newHeight = double.tryParse(message.message) ?? 300;
// 限制高度在 100~2000 之间,避免无限增大
newHeight = newHeight.clamp(100, 2000);
setState(() {
_webViewHeight = double.parse(message.message); // 动态更新高度
});
},
)
..loadRequest(
Uri.dataFromString(
htmlPage,
mimeType: 'text/html',
encoding: Encoding.getByName('utf-8'),
),
);
使用
Container(
width: MediaQuery.of(context).size.width,
height: _webViewHeight,
child: WebViewWidget(controller: _webViewController!),
),