Flutter中如何实现容器背景颜色的旋转动画?
解决方案
要实现黑胶唱片式的渐变旋转效果,核心是让渐变载体为足够大的圆形(避免旋转时露出空白),并对其进行持续旋转动画。以下是修改后的代码:
import 'package:flutter/material.dart'; class SplashPage extends StatefulWidget { const SplashPage({super.key}); @override State<SplashPage> createState() => _SplashPageState(); } class _SplashPageState extends State<SplashPage> with SingleTickerProviderStateMixin { late final AnimationController _animationController; @override void initState() { super.initState(); _animationController = AnimationController( vsync: this, duration: const Duration(seconds: 3), // 调整速度,模拟黑胶转速 upperBound: double.infinity, // 支持无限循环 ); // 页面加载后开始持续旋转 WidgetsBinding.instance.addPostFrameCallback((_) { _animationController.repeat(); }); } @override void dispose() { _animationController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { final screenSize = MediaQuery.of(context).size; // 圆形尺寸设为屏幕宽度的2倍,确保旋转时完全覆盖屏幕 final circleSize = screenSize.width * 2; return SizedBox( width: double.infinity, height: double.infinity, child: Stack( children: [ RotationTransition( // 直接使用控制器驱动旋转,repeat模式下自动循环0到1的旋转进度 turns: _animationController, child: Center( child: SizedBox( width: circleSize, height: circleSize, child: Container( decoration: const BoxDecoration( shape: BoxShape.circle, gradient: LinearGradient( colors: [ Color(0xFF212657), Color(0xFF28346D), Color(0xFF33498E), Color(0xFF3A56A1), Color(0xFF3D5BA9), Color(0xFF405AA7), Color(0xFF7D538B), Color(0xFFAE4E74), Color(0xFFD14A64), Color(0xFFE7475A), Color(0xFFEF4757), ], begin: Alignment.topLeft, end: Alignment.bottomRight, stops: [ 0.02, 0.11, 0.28, 0.41, 0.5, 0.52, 0.73, 0.82, 0.92, 0.95, 1 ] ), ), ), ), ), ), // 其他叠加组件 ], ), ); } }
关键修改点说明
- 圆形渐变容器:将
BoxDecoration的shape设为BoxShape.circle,模拟黑胶唱片的圆形外观。 - 超大尺寸容器:把圆形容器的尺寸设为屏幕宽度的2倍,确保旋转过程中始终覆盖整个屏幕,避免露出边缘空白。
- 持续旋转动画:将
AnimationController设为无限循环模式(repeat()),并调整duration控制旋转速度,更贴近黑胶唱片的转动节奏。 - 优化控制器配置:移除了无用的
_isRotated变量,添加dispose()方法释放控制器资源,避免内存泄漏。
如果不需要圆形背景,仅需渐变本身旋转,可使用GradientRotation实现:
AnimatedBuilder( animation: _animationController, builder: (context, child) { return Container( decoration: BoxDecoration( gradient: GradientRotation( _animationController.value * 2 * 3.1415926, // 转换为弧度 ).transform( const LinearGradient( // 你的渐变参数 ), ), ), ); }, )
内容的提问来源于stack exchange,提问作者Elder Carvalho
相关产品推荐
相关产品推荐

