You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中如何为WebView添加圆形进度指示器优化支付页面

解决方案

问题出在WebView加载HTML字符串的过程中,会短暂显示未解析的原始内容。通过添加加载状态管理,在WebView完成加载前显示进度指示器即可解决。

修改步骤:

  1. 将CoreWebView改为StatefulWidget,用于跟踪加载状态
  2. 添加加载状态变量,控制进度指示器的显示/隐藏
  3. 利用WebView的onPageFinished回调监听加载完成事件
  4. 使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 04:55:31