Flutter Mobile Development · 课时

交错动画与编排式 AnimationControllers

使用时间间隔和曲线编排多个动画,构成协调的动画序列。

第 4 / 4 课13 个步骤

交错动画与编排式 AnimationControllers 是 CoddyKit 上的免费 Flutter Mobile Development 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Flutter Mobile Development 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Flutter Mobile Development 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

What Is a Staggered Animation?

A staggered animation is a sequence where several visual changes happen at different times within a single timeline, instead of all at once.

Think of a card that first fades in, then slides up, then its icon rotates. Each step starts and ends at a different point along one shared clock.

  • One AnimationController drives the master clock (0.0 to 1.0).
  • Each property gets its own slice of that clock via an Interval.
  • This keeps everything perfectly in sync because they share the same time source.

This lesson focuses on orchestrating multiple animations with intervals and curves to build choreographed sequences.

One Controller, Many Tweens

The core pattern: a single AnimationController defines the total duration, and you derive multiple Animation objects from it.

The controller value moves linearly from 0.0 to 1.0. Each animation reads that value but maps it to its own range and timing window.

  • controller.value is the shared progress.
  • Tween maps 0..1 to your target values (offsets, opacity, scale).
  • CurvedAnimation applies easing and timing windows.

Why one controller instead of many? Because synchronizing several independent controllers is error-prone. A single timeline guarantees the steps never drift apart.

// Conceptual mapping of a shared 0..1 clock to staggered slices.
void main() {
  // Master clock samples (what the controller would emit each frame).
  final samples = [0.0, 0.25, 0.5, 0.75, 1.0];

  // Opacity runs over the first half: interval [0.0, 0.5].
  double opacity(double t) {
    final local = ((t - 0.0) / (0.5 - 0.0)).clamp(0.0, 1.0);
    return local; // 0 -> 1 across the slice
  }

  // Slide runs over the second half: interval [0.5, 1.0].
  double slide(double t) {
    final local = ((t - 0.5) / (1.0 - 0.5)).clamp(0.0, 1.0);
    return 1.0 - local; // 1 -> 0 (slides into place)
  }

  for (final t in samples) {
    print('t=$t opacity=${opacity(t)} slideY=${slide(t)}');
  }
}

Intervals Carve Up the Timeline

An Interval is a curve that stays at 0.0 until its begin point, animates between begin and end, then stays at 1.0.

This is the key tool for staggering. By giving each animation a different interval, you decide when in the master timeline it plays.

  • Interval(0.0, 0.5) — plays in the first half.
  • Interval(0.5, 1.0) — plays in the second half.
  • Interval(0.2, 0.8) — starts a bit late, ends a bit early.

You can also nest a curve inside an interval to ease the motion within that slice.

// Simulate Flutter's Interval(begin, end, curve) math without Flutter.
class Interval {
  final double begin;
  final double end;
  Interval(this.begin, this.end);

  double transform(double t) {
    if (t <= begin) return 0.0;
    if (t >= end) return 1.0;
    return (t - begin) / (end - begin);
  }
}

void main() {
  final fade = Interval(0.0, 0.5);
  final rise = Interval(0.5, 1.0);
  for (final t in [0.0, 0.25, 0.5, 0.75, 1.0]) {
    print('t=$t fade=${fade.transform(t)} rise=${rise.transform(t)}');
  }
}

Building Staggered Animations in Flutter

Here is the idiomatic Flutter setup. Inside a State with SingleTickerProviderStateMixin, create one controller and several animations, each using a CurvedAnimation with an Interval.

  • vsync: this ties the controller to the screen's frame ticker.
  • Each CurvedAnimation combines an interval (timing) with a curve (easing).
  • Tween.animate(...) maps the curved progress to real values.

This is framework code, so it is not standalone-runnable, but it is the canonical structure you will reuse constantly.

class _CardState extends State<AnimatedCard>
    with SingleTickerProviderStateMixin {
  late final AnimationController _controller = AnimationController(
    duration: const Duration(milliseconds: 1200),
    vsync: this,
  );

  late final Animation<double> _opacity = Tween<double>(begin: 0, end: 1)
      .animate(CurvedAnimation(
    parent: _controller,
    curve: const Interval(0.0, 0.4, curve: Curves.easeIn),
  ));

  late final Animation<Offset> _slide = Tween<Offset>(
    begin: const Offset(0, 0.3),
    end: Offset.zero,
  ).animate(CurvedAnimation(
    parent: _controller,
    curve: const Interval(0.3, 0.8, curve: Curves.easeOut),
  ));

  late final Animation<double> _scale = Tween<double>(begin: 0.8, end: 1.0)
      .animate(CurvedAnimation(
    parent: _controller,
    curve: const Interval(0.6, 1.0, curve: Curves.elasticOut),
  ));

  @override
  void initState() {
    super.initState();
    _controller.forward();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }
}

Overlapping vs Sequential Slices

The magic of choreography is in how intervals overlap. You rarely want hard cuts where one step fully finishes before the next begins.

  • Sequential: Interval(0.0, 0.3) then Interval(0.3, 0.6) — clean, distinct steps.
  • Overlapping: Interval(0.0, 0.5) and Interval(0.3, 0.8) — the second starts while the first is still finishing. This feels organic and fluid.

Overlap creates the sense that motion flows from one element into the next, which is the hallmark of polished, choreographed UI.

class Interval {
  final double begin, end;
  Interval(this.begin, this.end);
  double transform(double t) {
    if (t <= begin) return 0.0;
    if (t >= end) return 1.0;
    return (t - begin) / (end - begin);
  }
}

void main() {
  // Overlapping slices: fade still finishing while rise begins.
  final fade = Interval(0.0, 0.5);
  final rise = Interval(0.3, 0.8);
  for (var i = 0; i <= 10; i++) {
    final t = i / 10;
    final overlapping = fade.transform(t) > 0 &&
        fade.transform(t) < 1 &&
        rise.transform(t) > 0;
    print('t=${t.toStringAsFixed(1)} '
        'fade=${fade.transform(t).toStringAsFixed(2)} '
        'rise=${rise.transform(t).toStringAsFixed(2)} '
        'overlap=$overlapping');
  }
}

Curves: Shaping Motion Within a Slice

An interval controls when; a curve controls how the motion feels inside that window.

  • Curves.easeOut — fast start, gentle stop. Great for entrances.
  • Curves.easeIn — slow start, fast end. Great for exits.
  • Curves.elasticOut — overshoots and settles. Adds playfulness.
  • Curves.fastOutSlowIn — Material's standard motion curve.

You can pass the curve directly to Interval(begin, end, curve: ...), so each slice carries both its timing and its easing.

// Approximate an ease-out curve (1 - (1-t)^3) over a slice.
double easeOut(double t) => 1 - (1 - t) * (1 - t) * (1 - t);

class Interval {
  final double begin, end;
  final double Function(double) curve;
  Interval(this.begin, this.end, this.curve);
  double transform(double t) {
    if (t <= begin) return 0.0;
    if (t >= end) return 1.0;
    final local = (t - begin) / (end - begin);
    return curve(local);
  }
}

void main() {
  final entrance = Interval(0.2, 0.8, easeOut);
  for (var i = 0; i <= 10; i++) {
    final t = i / 10;
    print('t=${t.toStringAsFixed(1)} -> '
        '${entrance.transform(t).toStringAsFixed(3)}');
  }
}

Choreographing a Multi-Element List

A common pattern: animate a list so each item appears slightly after the previous one. You compute each item's interval from its index.

Divide the timeline into staggered windows. Item i might start at i * step and run for a fixed duration, clamped to stay inside [0, 1].

  • Keep the per-item duration longer than the step so windows overlap.
  • Clamp end to 1.0 so late items still complete.

This produces the familiar 'cascading' reveal seen in well-designed mobile apps.

// Compute staggered [begin, end] windows for a list of items.
List<List<double>> staggerWindows(int count, double itemDuration) {
  final windows = <List<double>>[];
  final step = count > 1 ? (1.0 - itemDuration) / (count - 1) : 0.0;
  for (var i = 0; i < count; i++) {
    final begin = (i * step).clamp(0.0, 1.0);
    final end = (begin + itemDuration).clamp(0.0, 1.0);
    windows.add([begin, end]);
  }
  return windows;
}

void main() {
  for (final w in staggerWindows(5, 0.4)) {
    print('begin=${w[0].toStringAsFixed(2)} '
        'end=${w[1].toStringAsFixed(2)}');
  }
}

Driving the Whole Sequence with AnimatedBuilder

To render the choreography, wrap your widget tree in an AnimatedBuilder (or use FadeTransition / SlideTransition for individual animations).

  • AnimatedBuilder rebuilds only its builder when the controller ticks — efficient.
  • Read each derived animation's .value inside the builder.
  • The child parameter caches subtrees that do not depend on the animation.

Because every animation shares the one controller, a single forward() plays the entire choreographed sequence.

@override
Widget build(BuildContext context) {
  return AnimatedBuilder(
    animation: _controller,
    builder: (context, child) {
      return Opacity(
        opacity: _opacity.value,
        child: Transform.translate(
          offset: Offset(0, _slide.value.dy * 60),
          child: Transform.scale(
            scale: _scale.value,
            child: child,
          ),
        ),
      );
    },
    child: const Card(child: Padding(
      padding: EdgeInsets.all(16),
      child: Text('Choreographed!'),
    )),
  );
}

Replaying, Reversing, and Looping

Once your timeline is built, the controller gives you full transport control over the whole choreography at once.

  • forward() — play 0 to 1.
  • reverse() — play 1 to 0 (the choreography runs backwards).
  • repeat(reverse: true) — loop back and forth, ideal for ambient effects.
  • reset() then forward() — replay from scratch.

Tip: If you want exits to feel different from entrances, build separate intervals/curves and switch which animations you read based on direction, rather than just reversing.

Coordinating Two Controllers When Needed

Sometimes one timeline is not enough — for example a looping background pulse plus a one-shot entrance. Then you do use multiple controllers, but coordinate them deliberately.

  • Use a status listener to start controller B when controller A completes.
  • Or use TickerFuture: await _a.forward(); then _b.forward();
  • Always dispose every controller to avoid ticker leaks.

Prefer a single controller for tightly-synced choreography; reach for multiple only when the animations are genuinely independent in lifecycle or looping behavior.

Future<void> playSequence(
  AnimationController intro,
  AnimationController loop,
) async {
  // Await the one-shot entrance, then kick off the ambient loop.
  await intro.forward();
  loop.repeat(reverse: true);
}

// Chaining via a status listener is the alternative:
void chain(AnimationController a, AnimationController b) {
  a.addStatusListener((status) {
    if (status == AnimationStatus.completed) {
      b.forward();
    }
  });
  a.forward();
}

Common Pitfalls in Choreography

Staggered animations are easy to get subtly wrong. Watch for these:

  • Forgetting to dispose the controller — leaks the ticker and prints debug warnings.
  • Interval end past 1.0 — Interval asserts 0.0 ≤ begin ≤ end ≤ 1.0; clamp your computed windows.
  • Too many controllers — harder to sync; prefer one with intervals.
  • Curves on the wrong layer — nest the curve inside the Interval, not as a separate CurvedAnimation stacked on top, or easing compounds unexpectedly.
  • No overlap — purely sequential slices can feel robotic; add slight overlap.
// Guard your computed interval windows before passing to Flutter.
({double begin, double end}) safeWindow(double begin, double duration) {
  final b = begin.clamp(0.0, 1.0);
  final e = (begin + duration).clamp(0.0, 1.0);
  // Interval requires begin <= end; enforce it.
  return (begin: b, end: e < b ? b : e);
}

void main() {
  print(safeWindow(0.8, 0.5)); // end clamps to 1.0
  print(safeWindow(0.0, 0.3));
}

Quick Check: Designing the Stagger

You want three list items to fade and slide in one after another, fully synchronized, with a smooth cascading overlap. Which approach best fits Flutter's idiomatic choreography model?

Recap: Orchestrating Choreographed Animations

You learned how to build staggered, choreographed sequences in Flutter:

  • One AnimationController is the shared master clock (0.0 to 1.0) that keeps everything in sync.
  • Interval(begin, end, curve: ...) slices the timeline so each animation plays in its own window with its own easing.
  • Overlapping intervals create organic, flowing motion; purely sequential ones feel mechanical.
  • Derive each property with Tween.animate(CurvedAnimation(...)) and render via AnimatedBuilder or transition widgets.
  • Compute per-item windows from the index for cascading lists, and always clamp to [0, 1] and dispose controllers.
  • Use multiple controllers only when lifecycles are genuinely independent (e.g., a one-shot entrance plus an ambient loop).

Master one timeline, slice it with intervals and curves, and you can choreograph almost any mobile motion.

免费开始

用 AI 导师学习 Dart — 免费

在浏览器中编写并运行真实代码,获得全天候 AI 导师的即时帮助,并在网页或应用中继续学习。

课程
22
课程
88

常见问题解答

「交错动画与编排式 AnimationControllers」课时是免费的吗?

是的 — 「交错动画与编排式 AnimationControllers」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Flutter Mobile Development 课程的其余内容,请升级到 CoddyKit PRO。 Flutter Mobile Development 课程共包含 4 节课。

「交错动画与编排式 AnimationControllers」这节课中我会学到什么?

使用时间间隔和曲线编排多个动画,构成协调的动画序列。 你通过在浏览器中直接运行的动手代码来练习 Flutter Mobile Development,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Flutter Mobile Development 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Flutter Mobile Development 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。

「交错动画与编排式 AnimationControllers」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Flutter Mobile Development 课中编写并运行代码吗?

能。每节 Flutter Mobile Development 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 嵌入 Rive 资源与控制器
  2. 状态机与输入驱动的运动
  3. Hero 转场与共享元素运动
  4. 交错动画与编排式 AnimationControllers
← 返回 Flutter Mobile Development