Flutter中如何为Container添加三色线性渐变背景动画?
三色线性渐变背景动画实现方案
Flutter 实现方案
通过AnimatedBuilder结合渐变偏移动画,实现类似动图的滑动渐变效果,仅使用3种颜色:
import 'package:flutter/material.dart'; class GradientAnimatedContainer extends StatefulWidget { const GradientAnimatedContainer({super.key}); @override State<GradientAnimatedContainer> createState() => _GradientAnimatedContainerState(); } class _GradientAnimatedContainerState extends State<GradientAnimatedContainer> with SingleTickerProviderStateMixin { late AnimationController _animController; late Animation<double> _offsetAnim; @override void initState() { super.initState(); // 创建循环反向动画控制器 _animController = AnimationController( duration: const Duration(seconds: 3), vsync: this, )..repeat(reverse: true); // 定义偏移量动画范围 _offsetAnim = Tween<double>(begin: -1.0, end: 1.0).animate(_animController); } @override void dispose() { _animController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( body: Center( child: AnimatedBuilder( animation: _offsetAnim, builder: (context, child) { return Container( width: 300, height: 300, decoration: BoxDecoration( gradient: LinearGradient( // 自定义三种渐变颜色 colors: const [Colors.purple, Colors.blue, Colors.cyan], begin: Alignment.topLeft, end: Alignment.bottomRight, // 通过偏移量控制渐变滑动 transform: GradientTransform.translate( dx: _offsetAnim.value, dy: _offsetAnim.value, ), ), ), ); }, ), ), ); } }
核心逻辑:
- 利用
GradientTransform.translate动态改变渐变的偏移位置 - 动画控制器循环反向执行,实现渐变来回滑动的效果
- 固定使用三种颜色,可直接替换为你需要的色值
Web CSS 实现方案
如果是前端场景,用CSS也能快速实现:
.gradient-box { width: 300px; height: 300px; /* 定义三色线性渐变 */ background: linear-gradient(45deg, #9c27b0, #2196f3, #00bcd4); /* 放大背景尺寸,预留滑动空间 */ background-size: 200% 200%; /* 执行渐变滑动动画 */ animation: gradientShift 3s ease-in-out infinite alternate; } @keyframes gradientShift { 0% { background-position: 0% 50%; } 100% { background-position: 100% 50%; } }
核心逻辑:
- 通过
background-size将渐变背景放大,让滑动效果可见 - 用
@keyframes控制background-position的变化,实现渐变滑动 - 动画无限交替反向,和动图效果一致
内容的提问来源于stack exchange,提问作者Elder Carvalho
相关产品推荐
相关产品推荐

