Flutter 动画系统
Flutter 的动画从"加一行就好"到"完全自定义曲线"都覆盖。按学习顺序:
隐式动画(AnimatedXxx) ← 80% 场景够用
显式动画(AnimationController) ← 复杂联动
Hero / 共享元素 ← 跨页面动画
Lottie / Rive ← 设计师导出的复杂动画一、隐式动画:加个 Animated 前缀
最简单的动画方式。给 Widget 一个目标值,它自己插值过去。
class Demo extends StatefulWidget {
@override State<Demo> createState() => _DemoState();
}
class _DemoState extends State<Demo> {
bool _big = false;
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () => setState(() => _big = !_big),
child: AnimatedContainer(
duration: const Duration(milliseconds: 300),
curve: Curves.easeOut,
width: _big ? 200 : 100,
height: _big ? 200 : 100,
color: _big ? Colors.blue : Colors.red,
),
);
}
}setState 改值 → AnimatedContainer 自动插值 300ms 过去。
常用隐式动画 Widget
| Widget | 用途 |
|---|---|
AnimatedContainer | 颜色 / 尺寸 / 边框 / decoration |
AnimatedOpacity | 透明度 |
AnimatedPositioned | Stack 内部位置 |
AnimatedAlign | 对齐方式 |
AnimatedPadding | 内边距 |
AnimatedDefaultTextStyle | 文字样式 |
AnimatedSwitcher | 子 Widget 切换 |
AnimatedCrossFade | 两个子之间淡入淡出 |
TweenAnimationBuilder | 自定义任意值 |
TweenAnimationBuilder:任意值都能动
TweenAnimationBuilder<double>(
tween: Tween(begin: 0, end: progress),
duration: const Duration(milliseconds: 500),
builder: (_, value, __) => CircularProgressIndicator(value: value),
)进度从 0 平滑跳到 progress。
AnimatedSwitcher:子 Widget 替换动画
AnimatedSwitcher(
duration: const Duration(milliseconds: 300),
child: Text(
'$count',
key: ValueKey(count), // ⚠️ 必须有 Key 才能识别"换了"
),
)回顾 07:Key 决定 Element 是不是同一个。这里没 Key,Flutter 复用 Element 只换字,根本不算"切换"。
二、显式动画:AnimationController
复杂动画、要精确控制时间/方向/暂停的,用控制器。
三件套
AnimationController:控制时间(开始/暂停/反向/进度)
Tween :值的范围(0 → 1、Colors.red → Colors.blue)
Curve :插值曲线(线性、回弹、easeOut)最小例子
class _DemoState extends State<Demo> with SingleTickerProviderStateMixin {
late AnimationController _ctrl;
late Animation<double> _anim;
@override
void initState() {
super.initState();
_ctrl = AnimationController(
vsync: this,
duration: const Duration(seconds: 1),
);
_anim = CurvedAnimation(parent: _ctrl, curve: Curves.easeOut);
_ctrl.repeat(reverse: true); // 来回循环
}
@override
void dispose() {
_ctrl.dispose(); // ⚠️ 必须释放
super.dispose();
}
@override
Widget build(BuildContext context) {
return AnimatedBuilder(
animation: _anim,
builder: (_, __) => Opacity(
opacity: _anim.value,
child: const FlutterLogo(size: 100),
),
);
}
}vsync = this 是什么?
vsync 让 AnimationController 跟屏幕刷新率同步,不可见时自动暂停。
- 一个 Controller 用
SingleTickerProviderStateMixin - 多个用
TickerProviderStateMixin
常用 Curve
Curves.linear // 匀速
Curves.easeIn / easeOut / easeInOut
Curves.bounceOut // 落地回弹
Curves.elasticOut // 弹簧
Curves.fastOutSlowIn // Material 默认Tween:任意值范围
final colorAnim = ColorTween(begin: Colors.red, end: Colors.blue).animate(_ctrl);
final offsetAnim = Tween<Offset>(
begin: Offset.zero,
end: const Offset(1, 0),
).animate(_ctrl);AnimatedBuilder vs AnimatedWidget
// AnimatedBuilder:不抽组件
AnimatedBuilder(
animation: _anim,
builder: (_, child) => Opacity(opacity: _anim.value, child: child),
child: const FlutterLogo(size: 100), // 静态部分,不重建
)
// AnimatedWidget:抽成独立类
class FadeBox extends AnimatedWidget {
const FadeBox({required Animation<double> a, super.key}) : super(listenable: a);
Animation<double> get a => listenable as Animation<double>;
@override
Widget build(BuildContext context) =>
Opacity(opacity: a.value, child: const FlutterLogo());
}三、Transition Widget:封装好的常用动画
不想自己写 Transform / Opacity 了,直接用:
FadeTransition(opacity: _anim, child: FlutterLogo())
ScaleTransition(scale: _anim, child: FlutterLogo())
SlideTransition(position: _offsetAnim, child: FlutterLogo())
RotationTransition(turns: _anim, child: FlutterLogo())
SizeTransition(sizeFactor: _anim, child: FlutterLogo())四、Stagger / 多段动画
不同子动画在不同时间段触发:
final fade = Tween<double>(begin: 0, end: 1).animate(
CurvedAnimation(parent: _ctrl, curve: const Interval(0.0, 0.5, curve: Curves.easeIn)),
);
final slide = Tween<Offset>(begin: const Offset(0, 1), end: Offset.zero).animate(
CurvedAnimation(parent: _ctrl, curve: const Interval(0.5, 1.0, curve: Curves.easeOut)),
);Interval(0.0, 0.5) 表示这个子动画在总时长的前半段跑。
或者用 AnimationController + 多个 addStatusListener 串联:
_ctrl1.addStatusListener((s) {
if (s == AnimationStatus.completed) _ctrl2.forward();
});flutter_staggered_animations 包提供更便捷的列表交错动画:
AnimationLimiter(
child: Column(
children: AnimationConfiguration.toStaggeredList(
duration: const Duration(milliseconds: 375),
childAnimationBuilder: (w) => SlideAnimation(
verticalOffset: 50,
child: FadeInAnimation(child: w),
),
children: items.map((i) => ItemTile(i)).toList(),
),
),
)五、Hero:跨页面共享元素
详情页打开时,缩略图变大平滑过渡到大图,这种叫 Hero 动画。
// 列表页
Hero(
tag: 'photo-${item.id}',
child: Image.network(item.thumb),
)
// 详情页
Hero(
tag: 'photo-${item.id}', // tag 必须一致
child: Image.network(item.full),
)Flutter 自动找到两个 tag 相同的 Hero,在路由切换时插一段 transition。
⚠️ 注意:
- tag 必须全局唯一
- 同一时刻树里同一 tag 不能有两个
- 列表里要用唯一 id 拼 tag
自定义 flightShuttleBuilder
需要"飞行中"的 widget 跟两端不同(比如圆角变方角):
Hero(
tag: 'photo-1',
flightShuttleBuilder: (_, anim, __, fromCtx, toCtx) {
return RotationTransition(
turns: anim,
child: const Icon(Icons.star),
);
},
child: ...,
)六、自定义 PageRouteBuilder:页面切换动画
Navigator.push(
context,
PageRouteBuilder(
pageBuilder: (_, anim, __) => DetailPage(),
transitionsBuilder: (_, anim, __, child) {
return FadeTransition(
opacity: anim,
child: SlideTransition(
position: Tween<Offset>(begin: const Offset(0, 0.1), end: Offset.zero)
.animate(anim),
child: child,
),
);
},
transitionDuration: const Duration(milliseconds: 250),
),
);go_router 同理,在 GoRoute 里用 pageBuilder 返回 CustomTransitionPage。
七、Lottie:设计师导出的 JSON 动画
设计师在 After Effects 用 Bodymovin 插件导出 .json,前端直接播。
dependencies:
lottie: ^3.1.2Lottie.asset('assets/loading.json')
Lottie.network('https://.../animation.json')
// 控制播放
final ctrl = AnimationController(vsync: this);
Lottie.asset(
'assets/loading.json',
controller: ctrl,
onLoaded: (composition) {
ctrl
..duration = composition.duration
..forward();
},
)优点:矢量、尺寸小、可复用 Web 资源 缺点:复杂动画文件不算小,部分滤镜效果支持不全
八、Rive:可交互的设计动画
比 Lottie 更进一步——动画可以有状态机(idle / hover / press / success),前端直接通过 input 切换。
dependencies:
rive: ^0.13.13RiveAnimation.asset(
'assets/button.riv',
artboard: 'Button',
stateMachines: const ['State Machine 1'],
onInit: (artboard) {
final ctrl = StateMachineController.fromArtboard(artboard, 'State Machine 1');
artboard.addController(ctrl!);
final pressed = ctrl.findInput<bool>('pressed') as SMIBool;
pressed.value = true;
},
)适合:按钮交互、引导动画、复杂 SVG-like 内容。
九、Material 自带的动画
| Widget | 效果 |
|---|---|
InkWell / InkResponse | 水波纹 |
Material 弹起 | 点击阴影变化 |
FloatingActionButton | Hero 默认开启 |
OpenContainer(animations 包) | 容器扩展为新页面 |
SharedAxisTransition | 平移切换 |
animations 包提供 Material Motion 系列:
dependencies:
animations: ^2.0.11OpenContainer(
closedBuilder: (_, open) => CardItem(onTap: open),
openBuilder: (_, __) => DetailPage(),
)十、动画性能要点
能用 RepaintBoundary 就用:把动画区域圈起来,Flutter 不会重绘外面
dartRepaintBoundary(child: AnimatedContainer(...))避免 SetState 全页面重建:用
AnimatedBuilder+child参数:dartAnimatedBuilder( animation: _ctrl, builder: (_, child) => Transform.rotate(angle: _ctrl.value, child: child), child: const ExpensiveWidget(), // 只构建一次 )Lottie 大文件用 cache:
Lottie.asset默认会缓存,但要避免每帧重建profile 模式下测:debug 模式动画一定卡,看真实性能用 profile
慢动画启动时:用
WidgetsBinding.instance.addPostFrameCallback等首帧渲染完再启动,避免抢占首帧
十一、常见坑
1. 忘记 dispose AnimationController
→ 内存泄漏,定时器一直跑(回顾 06 生命周期)
@override
void dispose() {
_ctrl.dispose();
super.dispose();
}2. AnimatedSwitcher 里 child 没 Key
AnimatedSwitcher(
duration: const Duration(milliseconds: 200),
child: Text(label), // ❌ 没 Key,文字变了不会触发动画
)
// ✅
child: Text(label, key: ValueKey(label)),3. Hero tag 重复
同一时刻两个 Hero(tag: 'a') 在树上 → 报错。
4. 动画期间触发新动画
_ctrl.forward();
_ctrl.forward(); // 第二次没效果(已经在跑)需要先 _ctrl.reset() 或 _ctrl.value = 0。
5. 在 build 里启动动画
@override
Widget build(BuildContext context) {
_ctrl.forward(); // ❌ 每次重建都启动
...
}应该在 initState 或事件回调里启。
十二、选型决策树
要做什么?
├─ 简单状态切换(尺寸/颜色/位置/透明度)
│ → AnimatedXxx 隐式动画
│
├─ 自定义曲线 / 多个 Widget 联动
│ → AnimationController + AnimatedBuilder
│
├─ 跨页面元素过渡
│ → Hero
│
├─ 列表项交错入场
│ → flutter_staggered_animations
│
├─ 设计师给的复杂动画
│ → Lottie(只播放)
│ → Rive(需要交互/状态机)
│
└─ 容器变成页面
→ OpenContainer(animations 包)十三、心智模型
隐式动画 = "你给目标值,我帮你过渡"
显式动画 = "你拿着控制器,我听你的"
Hero = "两个 Widget 共享 tag,我自动飞过去"
Lottie = "你设计师怎么画,我怎么播"
Rive = "动画自己有大脑,我只发信号"选用原则:先隐式,搞不定再显式。99% 不需要 30 行 AnimationController,加一句 AnimatedContainer 就完事了。