用flutter实现一个卡片反转的动画效果
- User
用flutter实现一个卡片反转的动画效果
Assistant
好的,我们来用 Flutter 实现一个卡片翻转的动画效果。
这个效果的核心是使用
Transform控件进行 3D 旋转,并结合AnimationController来控制旋转的角度和速度。我们将实现一个围绕 Y 轴(水平方向)翻转的卡片。
核心思路:
AnimationController: 管理动画的播放、暂停、反转和持续时间。Tween: 定义动画值的范围,从 0 到pi(180度),这代表卡片翻转的整个过程。TransformwithMatrix4: 实现 3D 旋转。Matrix4.identity()..setEntry(3, 2, 0.001)..rotateY(angle)是关键,setEntry(3, 2, 0.001)添加了透视效果,让 3D 翻转看起来更真实。- 条件渲染: 在动画进行到一半(90度,即
pi/2)时,切换显示卡片的正面和背面。
代码实现:
import 'dart:math'; // 导入 math 库用于 pi import 'package:flutter/material.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( title: '卡片翻转动画', theme: ThemeData( primarySwatch: Colors.blue, ), home: const CardFlipScreen(), ); } } class CardFlipScreen extends StatefulWidget { const CardFlipScreen({super.key}); @override State<CardFlipScreen> createState() => _CardFlipScreenState(); } class _CardFlipScreenState extends State<CardFlipScreen> with SingleTickerProviderStateMixin { late AnimationController _controller; late Animation<double> _animation; bool _isFront = true; // 标记当前显示的是正面还是背面 @override void initState() { super.initState(); _controller = AnimationController( vsync: this, duration: const Duration(milliseconds: 600), // 动画时长 ); // 从 0 到 pi (180度) 的旋转动画 _animation = Tween<double>(begin: 0, end: pi).animate(_controller) ..addListener(() { // 在动画进行到一半时(90度),切换 _isFront 状态 if (_controller.value >= 0.5) { if (_isFront) { setState(() { _isFront = false; }); } } else { if (!_isFront) { setState(() { _isFront = true; }); } } }); } @override void dispose() { _controller.dispose(); super.dispose(); } void _flipCard() { if (_controller.isAnimating) { // 如果正在动画,则不响应点击,避免奇怪行为 return; } if (_controller.isCompleted) { _controller.reverse(); // 从背面翻回正面 } else { _controller.forward(); // 从正面翻到背面 } } // 构建卡片正面 Widget _buildFrontCard() { return Container( width: 250, height: 350, decoration: BoxDecoration( color: Colors.blueAccent, borderRadius: BorderRadius.circular(15), boxShadow: [ BoxShadow( color: Colors.black.withOpacity(0.3), spreadRadius: 2, blurRadius: 5, offset: const Offset(0, 3), ), ], ), child: const Center( child: Text( '卡片正面', style: TextStyle( color: Colors.white, fontSize: 30, fontWeight: FontWeight.bold, ), ), ), ); } // 构建卡片背面 Widget _buildBackCard() { return Container( width: 250, height: 350, decoration: BoxDecoration( color: Colors.purpleAccent, borderRadius: BorderRadius.circular(15), boxShadow: [ BoxShadow( color: Colors.black.withOpacity(0.3), spreadRadius: 2, blurRadius: 5, offset: const Offset(0, 3), ), ], ), child: const Center( child: Text( '卡片背面', style: TextStyle( color: Colors.white, fontSize: 30, fontWeight: FontWeight.bold, ), ), ), ); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('卡片翻转效果'), ), body: Center( child: GestureDetector( onTap: _flipCard, child: AnimatedBuilder( animation: _animation, builder: (context, child) { // 根据动画值和 _isFront 状态计算实际应用的旋转角度 // 当 _isFront 为 true 时,使用 _animation.value (0 -> pi/2) // 当 _isFront 为 false 时,使用 _animation.value + pi (pi/2 -> pi 后的实际翻转角度) // 关键点:当卡片翻过90度时,我们实际上是把背面卡片旋转回来,让它从-90度(背面可见)到0度(正面可见)。 // 所以当 _isFront 为 false 时,我们需要将旋转角度调整到 -180 到 0 之间,或者直接让 _animation.value 超过 pi/2 后,计算其相对背面视角的角度。 // 最简洁的方案:根据当前显示的卡片,应用一个相对其自身的旋转。 final angle = _animation.value; final transformAngle = _isFront ? angle : angle + pi; // 当显示背面时,给它一个初始180度偏移 // 这个 if 语句在动画的中间点切换卡片内容 // 在 0-90 度显示正面,90-180 度显示背面 Widget currentCard = _isFront ? _buildFrontCard() : _buildBackCard(); // 重要:如果显示的是背面,我们还需要将它的内容翻转过来,因为它是从背面看向正面的。 // 这里的 `_isFront` 已经正确控制了显示哪个卡片, // 但 `transformAngle` 需要更精细的控制,确保翻转是平滑的。 // 如果 _isFront 为 true,角度从 0 到 pi/2 // 如果 _isFront 为 false,角度从 -pi/2 到 0 // 实际卡片翻转的透视效果和旋转 return Transform( alignment: Alignment.center, transform: Matrix4.identity() ..setEntry(3, 2, 0.001) // 增加透视效果,使 3D 旋转更真实 ..rotateY( _isFront ? angle : angle - pi), // 关键的旋转逻辑 child: currentCard, ); }, ), ), ), ); } }代码解析:
_CardFlipScreenStatewithSingleTickerProviderStateMixin: 混入SingleTickerProviderStateMixin是为了AnimationController的vsync参数,它确保动画在每一帧都正确更新。AnimationController _controller:duration: const Duration(milliseconds: 600): 动画从开始到结束需要 600 毫秒。
Animation<double> _animation:Tween<double>(begin: 0, end: pi).animate(_controller): 创建一个动画,其值从 0 渐变到pi(Math.PI,即 180 度)。这个_animation的值将直接作为旋转角度。addListener(() { ... }): 监听动画值的变化。当动画进度 (_controller.value) 达到 0.5 (即旋转到 90 度) 时,我们切换_isFront状态。这个_isFront状态将决定当前应该显示的是正面卡片还是背面卡片。
_flipCard()方法:- 当点击卡片时调用。
_controller.isCompleted:检查动画是否已完成(卡片显示背面)。如果是,则调用_controller.reverse()将卡片翻回正面。- 否则,调用
_controller.forward()将卡片从正面翻到背面。
_buildFrontCard()和_buildBackCard():- 简单的
Container控件,用于表示卡片的正面和背面,带有不同的颜色和文本,以便区分。
- 简单的
AnimatedBuilder:animation: _animation: 监听_animation的变化。每当_animation的值更新时,builder函数就会被调用。builder: (context, child) { ... }:final angle = _animation.value;: 获取当前的旋转角度值 (0 到pi)。final transformAngle = _isFront ? angle : angle - pi;: 这是实现翻转效果的关键。- 当
_isFront为true(卡片正在从正面翻转到背面,或者已经显示正面):直接使用angle。angle会从0增大到pi/2。 - 当
_isFront为false(卡片正在从背面翻转到正面,或者已经显示背面):此时卡片已经过了 90 度,angle的值在pi/2到pi之间。为了让背面卡片从面向我们的角度开始旋转,我们需要将其初始位置视为已旋转了 180 度,然后反向旋转。所以我们用angle - pi。当angle从pi/2变化到pi时,angle - pi就会从-pi/2变化到0,这正好是背面卡片从“面向远离”翻转到“面向我们”所需的变化。
- 当
Widget currentCard = _isFront ? _buildFrontCard() : _buildBackCard();: 根据_isFront状态动态选择要显示的卡片。Transform:alignment: Alignment.center: 确保旋转围绕卡片中心进行。transform: Matrix4.identity()..setEntry(3, 2, 0.001)..rotateY(transformAngle):Matrix4.identity(): 创建一个单位矩阵,作为 3D 变换的起点。..setEntry(3, 2, 0.001): 这个是透视参数。它将 3D 效果映射到 2D 屏幕上,使远处的物体看起来更小。值越小,透视效果越强。..rotateY(transformAngle): 沿着 Y 轴(垂直方向)旋转卡片,旋转角度就是我们计算出的transformAngle。
通过上述代码,你就可以在 Flutter 中实现一个平滑、带有 3D 透视效果的卡片翻转动画了。
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.