Flutter如何实现animatedrotation动画效果

在Flutter中想要实现AnimatedRotation动画效果,但不太清楚具体该怎么做。我看官方文档提到RotationTransition,但不知道和AnimatedRotation有什么区别?能否提供一个简单的代码示例展示如何让Widget实现平滑旋转动画?最好能说明如何控制旋转角度、持续时间以及曲线效果。另外,这种旋转动画对性能影响大吗?

2 回复

使用AnimatedRotation组件,设置turns属性控制旋转圈数,配合duration设置动画时长。例如:

AnimatedRotation(
  turns: _turns, // 0.0~1.0为一圈
  duration: Duration(seconds: 1),
  child: YourWidget(),
)

通过setState改变_turns值触发动画。

更多关于Flutter如何实现animatedrotation动画效果的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


在Flutter中实现AnimatedRotation动画效果,可以通过以下几种方式:

1. 使用AnimatedRotation Widget(推荐)

这是最简单的方法,适用于大多数旋转动画场景:

AnimatedRotation(
  turns: _rotationValue, // 旋转圈数(1.0 = 360度)
  duration: Duration(seconds: 1),
  child: Container(
    width: 100,
    height: 100,
    color: Colors.blue,
    child: Center(
      child: Text('旋转动画'),
    ),
  ),
)

2. 完整示例代码

import 'package:flutter/material.dart';

class RotationAnimationExample extends StatefulWidget {
  @override
  _RotationAnimationExampleState createState() => _RotationAnimationExampleState();
}

class _RotationAnimationExampleState extends State<RotationAnimationExample> {
  double _rotation = 0.0;

  void _rotate() {
    setState(() {
      _rotation += 0.25; // 每次旋转90度
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('旋转动画示例')),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            AnimatedRotation(
              turns: _rotation,
              duration: Duration(seconds: 1),
              curve: Curves.easeInOut,
              child: Container(
                width: 150,
                height: 150,
                decoration: BoxDecoration(
                  color: Colors.blue,
                  borderRadius: BorderRadius.circular(10),
                ),
                child: Icon(Icons.star, color: Colors.white, size: 50),
              ),
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: _rotate,
              child: Text('开始旋转'),
            ),
          ],
        ),
      ),
    );
  }
}

3. 主要参数说明

  • turns: 旋转圈数(1.0 = 360度,0.25 = 90度)
  • duration: 动画持续时间
  • curve: 动画曲线(如Curves.easeInOut)
  • child: 需要旋转的子Widget

4. 其他旋转动画方式

如果需要更复杂的控制,也可以使用RotationTransition

RotationTransition(
  turns: _animation,
  child: YourWidget(),
)

AnimatedRotation是最简单直接的旋转动画实现方式,适合大多数旋转需求。

回到顶部