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

Flutter中webview加载spinner背景透明度设置不生效如何解决?

问题原因

你的透明度设置没有生效是因为使用了IndexedStack组件,它的特性是同一时间仅渲染展示index参数对应的单个子元素,其他子元素不会被渲染到页面上。当你把position设为1显示加载层时,底层的WebView完全没有被渲染,半透明白色背景下没有内容,看起来就和不透明的白色效果一样,并不是opacity属性本身没生效。

修复方案
  • 把IndexedStack替换为Stack组件,Stack的特性是所有子组件按书写顺序堆叠渲染,后写的组件会盖在前写的组件上层
  • 用bool类型的isLoading变量控制加载层的显示隐藏,替换原来的position切换逻辑
  • (可选优化)将SpinKit的AnimationController提取为State的成员变量,避免每次build重复创建造成内存泄漏
修改后的核心代码
// 原有State类中删除int position变量,保留bool isLoading = false;
@override
Widget build(BuildContext context) {
  return WillPopScope(
    onWillPop: () => _goBack(context),
    child: Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: null,
      body: SafeArea(
        child: Stack(
          children: [
            WebView(
              initialUrl: 'https://google.com',
              javascriptMode: JavascriptMode.unrestricted,
              key: key,
              onPageStarted: (value) {
                setState(() {
                  isLoading = true;
                });
              },
              onPageFinished: (value) {
                setState(() {
                  isLoading = false;
                });
              },
              onWebViewCreated: (WebViewController webViewController) {
                _controllerCompleter.future
                    .then((value) => _controller = value);
                _controllerCompleter.complete(webViewController);
              },
            ),
            Visibility(
              visible: isLoading,
              child: Container(
                width: MediaQuery.of(context).size.width,
                height: MediaQuery.of(context).size.height,
                color: Colors.white.withOpacity(0.5),
                child: Center(
                  child: SpinKitDualRing(
                    color: Colors.pinkAccent,
                    size: 45.0,
                    controller: AnimationController(
                      vsync: this,
                      duration: const Duration(milliseconds: 1200),
                    ),
                  ),
                ),
              ),
            )
          ],
        ),
      ),
    ),
  );
}
可选优化(避免内存泄漏)

将动画控制器提取为State成员变量,统一管理生命周期:

// State类内添加成员变量
late AnimationController spinController;

@override
void initState() {
  super.initState();
  // 初始化动画控制器
  spinController = AnimationController(
    vsync: this,
    duration: const Duration(milliseconds: 1200),
  );
  if (Platform.isAndroid) WebView.platform = SurfaceAndroidWebView();
}

@override
void dispose() {
  // 页面销毁时释放动画控制器
  spinController.dispose();
  super.dispose();
}

之后SpinKit的controller参数直接传spinController即可。

内容的提问来源于stack exchange,提问作者codelone

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 02:45:01