Поэтапные и срежиссированные AnimationControllers
Оркестрируйте несколько анимаций с интервалами и кривыми для создания срежиссированных последовательностей.
«Поэтапные и срежиссированные AnimationControllers» — бесплатный урок Flutter Mobile Development на CoddyKit. Это урок 4 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения 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
AnimationControllerdrives 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.valueis the shared progress.Tweenmaps 0..1 to your target values (offsets, opacity, scale).CurvedAnimationapplies 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: thisties the controller to the screen's frame ticker.- Each
CurvedAnimationcombines 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)thenInterval(0.3, 0.6)— clean, distinct steps. - Overlapping:
Interval(0.0, 0.5)andInterval(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
endto 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).
AnimatedBuilderrebuilds only itsbuilderwhen the controller ticks — efficient.- Read each derived animation's
.valueinside the builder. - The
childparameter 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()thenforward()— 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 listenerto 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 —
Intervalasserts0.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 separateCurvedAnimationstacked 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
AnimationControlleris 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 viaAnimatedBuilderor 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.
Часто задаваемые вопросы
Урок «Поэтапные и срежиссированные AnimationControllers» бесплатный?
Да — полный текст урока «Поэтапные и срежиссированные AnimationControllers» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Flutter Mobile Development, подпишись на CoddyKit PRO. Курс Flutter Mobile Development содержит 4 уроков всего.
Чему я научусь в уроке «Поэтапные и срежиссированные AnimationControllers»?
Оркестрируйте несколько анимаций с интервалами и кривыми для создания срежиссированных последовательностей. Ты практикуешь Flutter Mobile Development с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Flutter Mobile Development?
Предыдущий опыт не требуется. Flutter Mobile Development на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 4 из 4.
Сколько времени занимает урок «Поэтапные и срежиссированные AnimationControllers»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Flutter Mobile Development?
Да. Каждый урок Flutter Mobile Development включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Встраивание ресурсов Rive и контроллеров
- Конечные автоматы и движение под управлением ввода
- Переходы Hero и движение общих элементов
- Поэтапные и срежиссированные AnimationControllers