Sub topic 15
Playing, reversing, repeating and listening to status
This chapter covers the methods that start, stop and steer an AnimationController, and the status values and listeners that report what the controller is doing. It assumes you know Dart (classes, mixins, closures), StatefulWidget and setState, and that you have already created a controller with vsync and disposed it, as covered in the earlier chapters on AnimationController and tickers.
The controller is a number that moves
An AnimationController produces a double called value. By default it runs from 0.0 to 1.0 (lowerBound and upperBound). Every playback method changes how value moves toward one of those bounds, or toward a target you pick. Tweens and curves, which you attach to the controller, only reshape that number.
The controller also has a status of type AnimationStatus. It has four values.
| Status | Meaning |
|---|---|
| `dismissed` | Stopped at the start (`value` is `lowerBound`). |
| `forward` | Running toward the end. |
| `reverse` | Running toward the start. |
| `completed` | Stopped at the end (`value` is `upperBound`). |
A newly created controller is dismissed. A stopped controller sitting between the bounds keeps the status of the last direction it ran in.
Playback methods
The core methods are listed below. Each of the first four returns a TickerFuture, a Future that completes when the animation finishes.
| Method | Effect |
|---|---|
| `forward({double? from})` | Animates toward `upperBound`. If `from` is given, jumps there first. |
| `reverse({double? from})` | Animates toward `lowerBound`. If `from` is given, jumps there first. |
| `repeat({min, max, reverse, period, count})` | Loops. With `reverse: true` it runs back and forth. |
| `animateTo(target, {duration, curve})` | Animates to a specific value, using the forward direction. |
| `stop({canceled})` | Stops where it is, without moving `value`. |
| `reset()` | Sets `value` to `lowerBound` immediately. |
| `value = x` | Jumps to `x` and stops any running animation. |
Calling a playback method while the controller is already running does not queue anything. The new call replaces the current motion, starting from the current value. This is what makes interruption smooth: reversing a half-finished animation moves back from the halfway point instead of snapping.
A toggle with forward and reverse
The example below rotates an icon a half turn when you tap it, and rotates it back on the next tap. It picks the direction from the current status.
import 'package:flutter/material.dart';
class ExpandArrow extends StatefulWidget {
const ExpandArrow({super.key});
@override
State<ExpandArrow> createState() => _ExpandArrowState();
}
class _ExpandArrowState extends State<ExpandArrow>
with SingleTickerProviderStateMixin {
late final AnimationController _controller = AnimationController(
vsync: this,
duration: const Duration(milliseconds: 300),
);
late final Animation<double> _turns = Tween<double>(begin: 0, end: 0.5)
.animate(CurvedAnimation(parent: _controller, curve: Curves.easeInOut));
void _toggle() {
if (_controller.isForwardOrCompleted) {
_controller.reverse();
} else {
_controller.forward();
}
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return IconButton(
onPressed: _toggle,
icon: RotationTransition(
turns: _turns,
child: const Icon(Icons.keyboard_arrow_down),
),
);
}
}isForwardOrCompleted is true when the status is forward or completed. It is the right test for a toggle. Checking status == AnimationStatus.completed alone would fail when the user taps mid-animation: the status is forward, so the code would call forward() again and nothing would reverse.
Repeating
repeat() runs the animation forever until you call stop(), reset(), or dispose the controller.
_controller.repeat(); // 0 -> 1, jump to 0, again
_controller.repeat(reverse: true); // 0 -> 1 -> 0 -> 1 ...
_controller.repeat(min: 0.2, max: 0.8, period: const Duration(seconds: 2));
_controller.repeat(count: 3, reverse: true);Three details matter here:
periodoverrides the controller'sdurationfor one full pass frommintomax. Without it, the pass takes a share ofdurationproportional to the range.countlimits the number of passes. In newer Flutter versions, arepeatwith acountreturns a future that completes when the last pass ends. An infinite repeat never completes its future normally.- With
reverse: false,valuejumps from the top back to the bottom with no animation, so the status does not go throughreverse. Withreverse: true, the status alternates betweenforwardandreverse, and never reportscompletedordismissedwhile looping.
Animating to a specific value
animateTo is useful for progress indicators and snapping behaviors.
await _controller.animateTo(0.75);
await _controller.animateTo(
1.0,
duration: const Duration(milliseconds: 150),
curve: Curves.easeOut,
);Its duration defaults to a share of the controller's duration based on the distance travelled. animateBack is the mirror image, for moving toward a lower value. Use animateWith for physics, for example a SpringSimulation, when you want motion that has no fixed duration.
Awaiting playback
Because playback methods return a TickerFuture, you can sequence steps with await instead of listeners.
Future<void> playOnce() async {
await _controller.forward();
await Future<void>.delayed(const Duration(milliseconds: 500));
if (!mounted) return;
await _controller.reverse();
}If the controller is stopped or disposed before the animation finishes, the TickerFuture never completes normally. It throws a TickerCanceled exception only if you attach .orCancel. Most of the time you do not want that, so use the plain await, and check mounted after every await before touching the controller again. A disposed controller throws if you call forward() on it.
try {
await _controller.forward().orCancel;
} on TickerCanceled {
// The animation was interrupted, for example by dispose() or stop().
}Listening to status
addStatusListener calls your function every time the status changes. addListener calls it on every tick, which is the same signal setState-based code uses, and is rarely what you want when a builder widget already rebuilds for you.
@override
void initState() {
super.initState();
_controller.addStatusListener(_onStatus);
}
void _onStatus(AnimationStatus status) {
switch (status) {
case AnimationStatus.completed:
debugPrint('reached the end');
case AnimationStatus.dismissed:
debugPrint('back at the start');
case AnimationStatus.forward:
case AnimationStatus.reverse:
break;
}
}Dart 3 switch statements on enums must cover every value, so the code above lists all four. Remove the listener with removeStatusListener if its lifetime is shorter than the controller's. Listeners attached to a controller are released when the controller is disposed, but a listener that captures a widget's State is a leak risk if you share the controller with another object.
Building a ping-pong loop by hand
repeat(reverse: true) is the simplest way to oscillate. A status listener lets you do the same thing with extra logic, such as pausing at each end or stopping after a condition.
void _onStatus(AnimationStatus status) {
if (status == AnimationStatus.completed) {
_controller.reverse();
} else if (status == AnimationStatus.dismissed) {
_controller.forward();
}
}Start it once with _controller.forward(). Prefer repeat when you need no extra logic, because it is shorter and has fewer states to get wrong.
Common errors
- Calling
forward()on a controller that is alreadycompleted. Nothing visible happens, becausevalueis already at the upper bound. Callreverse(),reset()first, or useforward(from: 0). - Using
status == completedas a toggle test. It misses the mid-animation case. UseisForwardOrCompletedorisAnimatinginstead. - Starting an animation inside
build.buildcan run many times. Start playback frominitState, an event handler, or a status listener. - Using a status listener to restart a
repeat.repeatalready loops. Adding a listener that callsforward()oncompletedcauses two loops to compete. - Forgetting
mountedafterawait. The widget may have been removed while the animation ran. - Expecting
completedwhilerepeat(reverse: true)runs. The status keeps alternating betweenforwardandreverse. Usecountif you need an end.
Exercise
A button toggles a panel with a controller. The handler is if (_controller.status == AnimationStatus.completed) { _controller.reverse(); } else { _controller.forward(); }. If the user taps again while the panel is still opening, the panel does not close. Why, and how do you fix it?
Show answer
While opening, the status is forward, not completed, so the handler takes the else branch and calls forward() again, which changes nothing. Test with _controller.isForwardOrCompleted instead, so a tap during opening calls reverse() and the animation turns around from its current value.
Exercise
Write the call that makes a controller oscillate between 0.2 and 0.8, taking 2 seconds for each one-way pass, and stopping after 4 passes.
Show answer
_controller.repeat(min: 0.2, max: 0.8, reverse: true, period: const Duration(seconds: 2), count: 4); The reverse: true makes it go back and forth, period sets the time for one pass between the bounds, and count ends the loop after four passes.