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

Flutter中如何实现Container颜色从中间向两侧扩散的动画效果

实现AnimatedContainer颜色从中间向两侧扩散的效果

AnimatedContainer默认的颜色过渡是整体色值渐变,没法直接实现从中间向两侧扩散的视觉效果。可以通过叠层容器+宽度动画来模拟这个效果:用Stack放置两个容器,底层显示初始颜色,上层显示目标颜色,通过动画让上层容器从宽度0扩展到充满整个容器且居中对齐,视觉上就像目标颜色从中间向两侧扩散覆盖。

修改后的代码如下:

ValueListenableBuilder(
  valueListenable: widget.controller._getLoading,
  builder: (context, _ControllerState controllerState, child) {
    final targetColor = _getColor(controllerState);
    // 根据当前状态获取对应的初始颜色(比如加载状态取空闲时的颜色,反之亦然)
    final initialColor = controllerState == _ControllerState.loading 
        ? _getColor(_ControllerState.idle) 
        : _getColor(_ControllerState.loading);

    return ClipRRect(
      borderRadius: widget.borderRadius ?? BorderRadius.circular(8),
      child: Stack(
        children: [
          // 底层容器:固定显示初始颜色
          Container(
            height: widget.height ?? 56,
            width: double.infinity,
            color: initialColor,
          ),
          // 上层动画容器:从中间向两侧展开,显示目标颜色
          AnimatedContainer(
            duration: const Duration(milliseconds: 700),
            curve: Curves.easeInOut,
            height: widget.height ?? 56,
            width: controllerState == _ControllerState.loading ? double.infinity : 0,
            alignment: Alignment.center,
            color: targetColor,
          ),
        ],
      ),
    );
  },
)

注意事项

  • 请根据你的_ControllerState枚举实际情况,调整initialColor的获取逻辑,确保它是当前状态的"对立"颜色。
  • 用ClipRRect包裹Stack是为了保留原代码的圆角效果,避免上层容器超出圆角范围。
  • 如果你的_getColor方法已经能正确返回不同状态对应的颜色,直接替换逻辑即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 17:25:23