跳到正文
CH 07异步与事件Flutter7 分钟阅读

动画与动效:隐式动画、显式动画、AnimationController

第 7 章 · 动画与动效:隐式动画、显式动画、AnimationController

本章示例examples/ch07-animation在线阅读源码下载 zip

run

$cd examples/ch07-animation && flutter run -d macos

已验证

  • flutter analyze 0 告警、flutter test 9 个用例全绿、flutter build macos --debug 真实构建并启动成功
  • 完整工程已打包:打包下载
本章目录 · 13 节

7.1 本章目标

  • 分清隐式动画(只给目标值)与显式动画(自己控制 0..1 进度);
  • 会用 AnimatedContainer、AnimatedOpacity、AnimatedSwitcher、TweenAnimationBuilder 覆盖 80% 的日常需求;
  • 会用 AnimationController + Tween + CurvedAnimation + AnimatedBuilder 写自定义动画,并正确 dispose;
  • 理解 Ticker 与"帧"的关系,知道为什么动画测试要 pump(Duration) 而不是 sleep;
  • 知道桌面端动画的性能底线:只重建需要动的子树。

7.2 两种动画,先分清再选

隐式动画(implicit) 显式动画(explicit)
你提供 目标值(尺寸/颜色/透明度) AnimationController + 每帧怎么画
谁管理进度 框架内部的 controller 你
需要 dispose 不需要 需要
典型 Widget AnimatedContainer、AnimatedOpacity、AnimatedAlign、AnimatedSwitcher、TweenAnimationBuilder AnimationController、AnimatedBuilder、CustomPainter
适用 "从 A 变到 B" 连续/可逆/需要跟手(滚动、拖拽、循环)
C/Go 类比 调用 AnimateTo(target) 这类 API 自己写每帧的 tick 回调 + 状态机

选择顺序:能用隐式就用隐式。只有当你要"暂停/倒放/重复/根据外部进度画"时,才上 AnimationController。

7.3 隐式动画:只告诉框架目标值

dartlib/src/animation_gallery.dart源文件
// examples/ch07-animation/lib/src/animation_gallery.dart
Center(
  child: AnimatedContainer(
    key: const Key('implicit-box'),
    duration: const Duration(milliseconds: 400),
    curve: Curves.easeInOut,
    width: _expanded ? 220 : 80,
    height: _expanded ? 120 : 80,
    decoration: BoxDecoration(
      color: _expanded ? const Color(0xFFAD1457) : const Color(0xFF4DB6AC),
      borderRadius: BorderRadius.circular(_expanded ? 24 : 8),
    ),
    child: Text(_expanded ? '展开' : '收起'),
  ),
)

setState 改 _expanded → Widget 重建 → AnimatedContainer 发现"目标值变了" → 用内部 controller 在旧值和新值之间插值 400ms。你一行 controller 代码都不用写,也不用 dispose。

测试里能看到中间帧的真实宽度:

dart
await tester.tap(find.byKey(const Key('implicit-toggle')));
await tester.pump();                                  // 动画开始
await tester.pump(const Duration(milliseconds: 200)); // 走到 400ms 的一半

final Size mid = tester.getSize(find.byKey(const Key('implicit-box')));
expect(mid.width, greaterThan(80));
expect(mid.width, lessThan(220));

await tester.pumpAndSettle();                         // 一直跑到没有动画
expect(tester.getSize(find.byKey(const Key('implicit-box'))).width, 220);

注意 pump() 与 pump(Duration) 的区别:前者推进一帧(不推进时钟),后者把虚拟时钟拨到指定时刻。动画测试不能 await Future.delayed——测试环境里那不是帧。pumpAndSettle 会一直 pump 到没有待处理动画为止,遇到 repeat() 的无限动画会直接超时。

7.4 TweenAnimationBuilder:给数字加动画

dart
TweenAnimationBuilder<double>(
  tween: Tween<double>(begin: 0, end: _target),
  duration: const Duration(milliseconds: 800),
  curve: Curves.easeOutCubic,
  builder: (BuildContext context, double value, Widget? child) => Text(value.toStringAsFixed(1)),
)

只要目标值变化,它就从当前值补到新目标。适合计数器、金额、进度数字——比手写 AnimationController 省一大截。

7.5 显式动画:AnimationController

dart
class _ExplicitCardState extends State<ExplicitCard> with SingleTickerProviderStateMixin {
  late final AnimationController _controller = AnimationController(
    vsync: this,                       // 需要一个 TickerProvider
    duration: const Duration(seconds: 1),
  );

  late final Animation<double> _curved = CurvedAnimation(
    parent: _controller,
    curve: Curves.easeOutBack,         // 把 0..1 的线性进度映射成"回弹"曲线
  );

  @override
  void dispose() {
    _controller.dispose();             // 必须:释放 Ticker
    super.dispose();
  }
  ...
}

四个概念:

概念 作用 C/Go 类比
Ticker 每帧回调一次的驱动器(由 SchedulerBinding 的 vsync 驱动) 定时器 + 垂直同步信号
AnimationController 保存 0..1 的进度,提供 forward()/reverse()/repeat() 手写状态机里的 progress 字段
Tween<T> 把 0..1 映射成 T(颜色、尺寸、偏移) 插值函数
CurvedAnimation 把 0..1 再映射一次(缓动曲线) 缓动函数表

vsync: this 要求 State 混入 SingleTickerProviderStateMixin(一个 State 只需要一个 Ticker 时用单数版;多个用 TickerProviderStateMixin)。忘了 dispose 的后果:debug 模式下 Flutter 会打印

text
A Ticker was still active when its TickerProvider was disposed.

并且 Ticker 继续跑 = 持续掉帧 + 泄漏。

AnimatedBuilder:只重建该重建的部分

dart
AnimatedBuilder(
  animation: _curved,
  builder: (BuildContext context, Widget? child) {
    return Transform.rotate(angle: _curved.value * math.pi / 2, child: /* ... */);
  },
)

AnimatedBuilder 的 builder 每帧调用一次,但只重建 builder 内部。如果把整个页面塞进 builder,每帧都重建整页——这是新手最常见的"动画卡顿"原因。

child 参数是给"不随动画变化的子树"用的优化位:传进去的 child 会被复用,不会每帧重建。

反向与重置

dart
_controller.forward();    // 0 → 1
_controller.reverse();    // 1 → 0
_controller.value = 0;    // 立刻跳到某个进度
_controller.repeat();     // 无限循环(测试里别用 pumpAndSettle)

测试断言了进度值:1s 动画走到 500ms 时约 50%(inInclusiveRange(40, 60) 留出插值误差),结束后是 100%。

7.6 AnimatedSwitcher:换内容时的交叉过渡

dart
AnimatedSwitcher(
  duration: const Duration(milliseconds: 300),
  transitionBuilder: (Widget child, Animation<double> animation) =>
      ScaleTransition(scale: animation, child: FadeTransition(opacity: animation, child: child)),
  child: Text(_faces[_index], key: ValueKey<int>(_index)),
)

必须给子级 Key:AnimatedSwitcher 靠 Key 判断"是不是同一个 child"。不给 Key 时它认为只是内容变了,直接替换,不做过渡——这是本章最容易踩的坑,没有之一。

测试能看到过渡期间新旧两个子级同时存在:

dart
await tester.tap(find.byKey(const Key('switcher-next')));
await tester.pump();
await tester.pump(const Duration(milliseconds: 100));
expect(find.text('😀'), findsOneWidget);   // 旧的在淡出
expect(find.text('😎'), findsOneWidget);   // 新的在淡入
await tester.pumpAndSettle();
expect(find.text('😀'), findsNothing);

7.7 动画与生命周期:还是 ch06 那套规则

动画属于"外部事件源",规则和 Stream 订阅完全一致:

资源 建在哪 释放
AnimationController 字段初始化 / initState dispose()
Ticker 由 Mixin 提供 随 controller
无限循环动画 initState 里 repeat() dispose 里 stop()
动画期间用 context 在 builder 内使用 卸载后不再回调

示例的"动画中途卸载"用例就是这条规则的回归测试:

dart
await tester.tap(find.byKey(const Key('play')));
await tester.pump(const Duration(milliseconds: 300));
await tester.pumpWidget(host(const Text('已卸载')));   // 动画还在跑就换树
await tester.pump(const Duration(seconds: 2));
expect(tester.takeException(), isNull);

去掉 _controller.dispose() 后,这个用例会以 A Ticker was still active... 失败。

7.8 桌面端的动画实践

场景 建议
悬停高亮 InkWell(onHover:) + AnimatedContainer,120–150ms 足够
页面切换 PageRouteBuilder 自定义过渡(ch09),桌面端可以更短(150ms)
列表增删 AnimatedList / AnimatedSwitcher,避免长列表整体重建
大量元素 少用 Opacity/ClipPath(离屏渲染开销大),优先 Transform 与颜色插值
减少动效 尊重系统的"减少动态效果"设置(MediaQuery.disableAnimationsOf(context))

桌面用户对"每帧重建整页"极其敏感(大窗口 + 高刷新率),所以 AnimatedBuilder 的范围一定要小。移动端同样适用,但桌面端更容易看出掉帧。

7.9 运行与验证

bash
cd examples/ch07-animation
flutter pub get && flutter analyze && flutter test
flutter run -d macos

本次真实验证:

text
No issues found! (ran in 1.9s)
00:00 +9: All tests passed!

✓ Built build/macos/Build/Products/Debug/ch07_animation.app
flutter: The Dart VM service is listening on http://127.0.0.1:58692/...

附:C/Go 代码对照:定时器 + 插值

c
/* C / Win32:16ms 定时器,手动算进度和缓动 */
static int t = 0;

void OnTimer(HWND hwnd) {
    t = (t + 16) % 1000;
    double p = t / 1000.0;                 // 0..1
    double eased = 1 - pow(1 - p, 3);      // easeOutCubic
    int size = (int)(80 + (220 - 80) * eased);
    MoveWindow(hBox, 20, 20, size, size, TRUE);
    InvalidateRect(hwnd, NULL, FALSE);
}
dart
// Flutter:隐式动画——只给目标值,插值与补帧由框架做
AnimatedContainer(
  duration: const Duration(milliseconds: 400),
  curve: Curves.easeOutCubic,
  width: expanded ? 220 : 80,
  height: expanded ? 220 : 80,
  child: const SizedBox.shrink(),
);

C 里你要自己管"当前进度、缓动函数、定时器、重绘";Dart 里显式动画也只需把同样的东西交给 AnimationController(它由 vsync 驱动,而不是随便的定时器)。

7.10 本章小结 + C/Go 对照清单

主题 C/Go 手写 Flutter 陷阱
补间 自己算 lerp(a,b,t) Tween / AnimatedContainer 忘了 curve 会显得生硬
帧驱动 定时器 + 双缓冲 Ticker + AnimationController 忘了 dispose → Ticker 泄漏
每帧重建范围 手绘整屏 AnimatedBuilder 局部重建 builder 包太大 → 掉帧
内容切换 手动淡出淡入 AnimatedSwitcher 子级没给 Key → 无过渡
循环动画 手动重置进度 controller.repeat() 测试里 pumpAndSettle 会超时
时间控制 sleep / clock_gettime pump(Duration) 虚拟时钟 测试里用 sleep = 不稳定

给 C/Go 老兵的三句话:

  1. 先问"能不能用隐式动画":AnimatedContainer 那类 Widget 省掉 90% 的 controller 代码。
  2. 显式动画的唯一负担是 dispose,和 ch06 的订阅一个道理。
  3. AnimatedBuilder 的边界就是"每帧要重跑的范围",边界越小越流畅。

下一章回到纯 Dart 进阶:mixin、extension、pub 包管理、isolate 并发。SingleTickerProviderStateMixin 到底是什么、为什么 Dart 需要 isolate 才能多核,都会在那一章讲清楚。