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
相关产品推荐
相关产品推荐

