Flutter中如何为WebView添加圆形进度指示器优化支付页面
解决方案
问题出在WebView加载HTML字符串的过程中,会短暂显示未解析的原始内容。通过添加加载状态管理,在WebView完成加载前显示进度指示器即可解决。
修改步骤:
- 将
CoreWebView改为StatefulWidget,用于跟踪加载状态 - 添加加载状态变量,控制进度指示器的显示/隐藏
- 利用WebView的
onPageFinished回调监听加载完成事件 - 使用
Stack布局叠加WebView和进度指示器
修改后的完整代码:
class CoreWebView extends StatefulWidget { final String htmlCode; const CoreWebView({Key? key, required this.htmlCode}) : super(key: key); @override State<CoreWebView> createState() => _CoreWebViewState(); } class _CoreWebViewState extends State<CoreWebView> { bool _isLoading = true; @override Widget build(BuildContext context) { return Stack( children: [ WebViewPlus( initialUrl: "https://example.com", javascriptMode: JavascriptMode.unrestricted, onWebViewCreated: (controller) { // 优化:直接加载原始HTML字符串,避免多余的转义包裹 controller.loadString(widget.htmlCode); }, onPageFinished: (url) { // 页面加载完成后隐藏指示器 setState(() { _isLoading = false; }); }, zoomEnabled: false, ), // 加载中显示圆形进度指示器(可替换为LinearProgressIndicator) if (_isLoading) Container( color: Colors.white, child: const Center( child: CircularProgressIndicator(), ), ), ], ); } }
额外优化点:
- 移除了
onWebViewCreated中多余的r"""包裹,直接加载原始HTML字符串,减少解析延迟 - 进度指示器背景色设为白色,保持和页面风格一致,避免视觉突兀
内容的提问来源于stack exchange,提问作者Doğukan Çiftçi
相关产品推荐
相关产品推荐

