Skip to content
TheChatArchiveThe Chat Archive
Geminigemini-2.5-flash· GoogleHugging Face LMArena Human Preference 140K

用flutter实现一个卡片反转的动画效果

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with o3-2025-04-16’s answer.
  1. User

    用flutter实现一个卡片反转的动画效果

  2. Gemini Assistant

    好的,我们来用 Flutter 实现一个卡片翻转的动画效果。

    这个效果的核心是使用 Transform 控件进行 3D 旋转,并结合 AnimationController 来控制旋转的角度和速度。

    我们将实现一个围绕 Y 轴(水平方向)翻转的卡片。

    核心思路:

    1. AnimationController: 管理动画的播放、暂停、反转和持续时间。
    2. Tween: 定义动画值的范围,从 0 到 pi (180度),这代表卡片翻转的整个过程。
    3. Transform with Matrix4: 实现 3D 旋转。Matrix4.identity()..setEntry(3, 2, 0.001)..rotateY(angle) 是关键,setEntry(3, 2, 0.001) 添加了透视效果,让 3D 翻转看起来更真实。
    4. 条件渲染: 在动画进行到一半(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,
                  );
                },
              ),
            ),
          ),
        );
      }
    }
    

    代码解析:

    1. _CardFlipScreenState with SingleTickerProviderStateMixin: 混入 SingleTickerProviderStateMixin 是为了 AnimationController 的 vsync 参数,它确保动画在每一帧都正确更新。
    2. AnimationController _controller:
      • duration: const Duration(milliseconds: 600): 动画从开始到结束需要 600 毫秒。
    3. 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 状态将决定当前应该显示的是正面卡片还是背面卡片。
    4. _flipCard() 方法:
      • 当点击卡片时调用。
      • _controller.isCompleted:检查动画是否已完成(卡片显示背面)。如果是,则调用 _controller.reverse() 将卡片翻回正面。
      • 否则,调用 _controller.forward() 将卡片从正面翻到背面。
    5. _buildFrontCard() 和 _buildBackCard():
      • 简单的 Container 控件,用于表示卡片的正面和背面,带有不同的颜色和文本,以便区分。
    6. 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 透视效果的卡片翻转动画了。

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.