Android生产环境Flutter应用WebView高度过大崩溃求助
Flutter WebView高度超过6000时Android端崩溃解决方案
问题概述
Android生产环境下的Flutter应用,当flutter_webview组件高度设置超过6000时触发致命崩溃,Play控制台捕获到JNI断言失败日志。
崩溃日志
Thread [FATAL:flutter/shell/platform/android/platform_view_android_jni_impl.cc(1327)] Check failed: fml::jni::CheckException(env). *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** pid: 0, tid: 25389 >>> com.example.app <<< backtrace: #00 pc 0x00000000000705ac /apex/com.android.runtime/lib64/bionic/libc.so (abort+160) #01 pc 0x0000000000321ed4 /data/app/com.example.app-65HExU3BHjvvqXZVKhlqTQ==/split_config.arm64_v8a.apk!libflutter.so
原因分析
该崩溃源于Android视图系统的底层限制:WebView作为原生视图,当高度超过系统允许的最大尺寸阈值时,会在布局测量或渲染阶段触发未捕获的JNI异常,而Flutter引擎的断言检查fml::jni::CheckException(env)会直接终止进程。
解决方案
1. 限制WebView最大高度
动态设置WebView高度上限,避免超过Android视图系统的阈值,建议参考屏幕高度设置合理上限(如屏幕高度的2-3倍):
double maxWebViewHeight = MediaQuery.of(context).size.height * 3; WebView( initialUrl: 'https://your-content-url.com', javascriptMode: JavascriptMode.unrestricted, gestureRecognizers: <Factory<OneSequenceGestureRecognizer>>{ Factory(() => EagerGestureRecognizer()), }, // 用min函数限制高度不超过上限 containerHeight: min(yourTargetHeight, maxWebViewHeight), );
2. 自适应内容高度+外层滚动容器
不给WebView设置固定超大高度,而是让其自适应实际内容高度,外层嵌套可滚动容器处理页面滚动:
double _webViewHeight = MediaQuery.of(context).size.height; WebViewController? _webViewController; SingleChildScrollView( child: SizedBox( height: _webViewHeight, child: WebView( initialUrl: 'https://your-content-url.com', javascriptMode: JavascriptMode.unrestricted, onPageFinished: (url) { // 通过JS获取页面实际高度并更新WebView尺寸 _webViewController?.runJavascriptReturningResult( "document.body.scrollHeight" ).then((result) { if (result != null) { setState(() { _webViewHeight = double.parse(result); }); } }); }, gestureRecognizers: <Factory<OneSequenceGestureRecognizer>>{ Factory(() => EagerGestureRecognizer()), }, onWebViewCreated: (controller) { _webViewController = controller; }, ), ), );
3. 调整WebView依赖版本
检查webview_flutter包版本,尝试升级到最新稳定版(或回退到已知无此问题的版本),新版本可能修复了大尺寸视图的JNI异常处理逻辑:
# pubspec.yaml dependencies: webview_flutter: ^4.4.0 # 替换为最新稳定版
4. 原生层捕获异常(进阶)
若必须使用超大高度,可自定义Android原生WebView,在测量阶段捕获异常避免崩溃:
// Android端自定义WebView class SafeWebView(context: Context) : WebView(context) { override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { try { super.onMeasure(widthMeasureSpec, heightMeasureSpec) } catch (e: Exception) { // 捕获测量异常,设置默认安全尺寸 setMeasuredDimension( getDefaultSize(0, widthMeasureSpec), getDefaultSize(0, heightMeasureSpec) ) } } }
随后通过Flutter平台通道将自定义WebView集成到Flutter应用中。
内容的提问来源于stack exchange,提问作者Chirag Prajapati
相关产品推荐
相关产品推荐

