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

Flutter中如何使用AnimatedBuilder实现颜色动画效果?

解决方案

你的需求完全可以实现,只需要在AnimatedBuilder的回调中根据动画控制器的当前进度匹配对应区间的动画值即可,以下是你现有代码的修正方案:

@override
Widget build(BuildContext context) {
  return AnimatedBuilder(
    animation: _controller,
    builder: (context, child) {
      Color currentColor;
      // 根据动画进度匹配对应区间的颜色
      if (_controller.value <= 0.2) {
        currentColor = _animFadeIn.value ?? Colors.pinkAccent;
      } else if (_controller.value >= 0.8) {
        currentColor = _animFadeOut.value ?? Colors.pinkAccent;
      } else {
        // 中间停留阶段固定为绿色
        currentColor = Colors.green;
      }
      return Container(
        height: 300,
        width: 100,
        decoration: BoxDecoration(
          color: currentColor,
        ));
    });
}

更简洁的优化写法

你也可以直接用TweenSequence将多段补间动画串接,不需要手动判断进度,代码更易维护:

class _AnimatedColorState extends State<AnimatedColor>
    with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  late Animation<Color?> _colorAnim;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      duration: const Duration(milliseconds: 1000),
      vsync: this,
    );

    _colorAnim = TweenSequence([
      // 第一段:20%时长 淡入 粉→绿
      TweenSequenceItem(
        tween: ColorTween(begin: Colors.pinkAccent, end: Colors.green)
            .chain(CurveTween(curve: Curves.fastOutSlowIn)),
        weight: 20,
      ),
      // 第二段:60%时长 停留绿色
      TweenSequenceItem(
        tween: ConstantTween<Color?>(Colors.green),
        weight: 60,
      ),
      // 第三段:20%时长 淡出 绿→粉
      TweenSequenceItem(
        tween: ColorTween(begin: Colors.green, end: Colors.pinkAccent)
            .chain(CurveTween(curve: Curves.fastOutSlowIn)),
        weight: 20,
      ),
    ]).animate(_controller);

    _controller.forward();
    // 如果需要循环播放可以替换为下面的代码
    // _controller.repeat();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return AnimatedBuilder(
      animation: _controller,
      builder: (context, child) {
        return Container(
          height: 300,
          width: 100,
          decoration: BoxDecoration(
            color: _colorAnim.value ?? Colors.pinkAccent,
          ));
      });
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 13:54:04