Sub topic 16
Disposing controllers and keeping animations cheap
This chapter assumes you can build a StatefulWidget with AnimationController, vsync, and AnimatedBuilder, as covered earlier in this tutorial. It explains what you must release when an explicit animation ends, and which habits keep animations from costing more than they should.
What a controller owns
An AnimationController holds two things that outlive a single build call:
- A
Ticker, registered with Flutter's scheduler. The ticker asks for a callback on every frame while the animation runs. - A list of listeners and status listeners that other objects have attached.
Flutter does not release either when the widget leaves the tree. The State object has to do it. dispose is the last call a State receives, so that is where the controller goes.
The rule is simple. Whichever object creates the controller disposes it. If a parent passes you an Animation, you did not create it, so you must not dispose it.
What goes wrong without dispose
Omitting dispose has two consequences.
First, debug builds throw. When the State is removed while the ticker is still active, the mixin reports an error that reads roughly "was disposed with an active Ticker". Release builds do not report it.
Second, the ticker keeps running. For a repeating animation, every frame keeps calling listeners on a widget that no longer exists. That wastes CPU and battery, and it can call setState on an unmounted State.
The reverse mistake also fails. Calling a method on a disposed controller, or disposing it twice, throws an error in debug builds.
Always dispose the controller before calling super.dispose():
@override
void dispose() {
_controller.dispose();
super.dispose();
}Choosing the right ticker mixin
SingleTickerProviderStateMixin creates exactly one ticker. That is correct when the State owns one controller, and it is slightly cheaper. If you create a second controller with vsync: this, debug builds fail an assertion.
Use TickerProviderStateMixin when a State owns several controllers, or when it creates and replaces controllers over time.
| Situation | Mixin |
|---|---|
| One controller for the lifetime of the State | `SingleTickerProviderStateMixin` |
| Two or more controllers | `TickerProviderStateMixin` |
| Controller recreated when a property changes | `TickerProviderStateMixin` |
Tickers that stop on their own
Flutter wraps each route in a TickerMode. When a route is covered by another route, TickerMode mutes its tickers, so animations on the hidden screen stop consuming frames. The controller's value does not advance while muted. It resumes when the route is visible again.
You can use the same widget directly. TickerMode(enabled: false, child: ...) pauses every ticker created beneath it, which is useful for off-screen tabs that you keep alive.
Reacting to widget changes
If a parent can change a parameter such as running or duration, handle it in didUpdateWidget. Do not create a new controller in build, because build runs far more often than you expect. The next example combines disposal, a pause switch, and the cost-saving habits covered below:
import 'package:flutter/material.dart';
class Spinner extends StatefulWidget {
const Spinner({super.key, this.running = true});
final bool running;
@override
State<Spinner> createState() => _SpinnerState();
}
class _SpinnerState extends State<Spinner>
with SingleTickerProviderStateMixin {
late final AnimationController _controller;
@override
void initState() {
super.initState();
_controller = AnimationController(
vsync: this,
duration: const Duration(seconds: 1),
);
if (widget.running) {
_controller.repeat();
}
}
@override
void didUpdateWidget(Spinner oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.running != oldWidget.running) {
if (widget.running) {
_controller.repeat();
} else {
_controller.stop();
}
}
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return RepaintBoundary(
child: RotationTransition(
turns: _controller,
child: const Icon(Icons.sync, size: 48),
),
);
}
}A stopped controller still holds its ticker. For a long-lived widget this costs almost nothing, because a stopped ticker schedules no frames.
Awaiting animations safely
forward(), reverse(), and animateTo() return a TickerFuture. If the controller is disposed mid-flight, the plain future never completes. Code after the await is silently skipped, which is usually harmless but hides bugs. Add .orCancel to get an error you can catch instead:
import 'package:flutter/material.dart';
class Bounce extends StatefulWidget {
const Bounce({super.key});
@override
State<Bounce> createState() => _BounceState();
}
class _BounceState extends State<Bounce>
with SingleTickerProviderStateMixin {
late final AnimationController _controller = AnimationController(
vsync: this,
duration: const Duration(milliseconds: 300),
);
Future<void> _playOnce() async {
try {
await _controller.forward().orCancel;
await _controller.reverse().orCancel;
} on TickerCanceled {
// The widget was disposed while the animation was running.
}
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: _playOnce,
child: ScaleTransition(
scale: Tween<double>(begin: 1, end: 1.3).animate(_controller),
child: const FlutterLogo(size: 64),
),
);
}
}Listeners you add yourself
A listener you attach to your own controller goes away with it. A listener you attach to an animation owned by someone else does not. Remove it in dispose:
@override
void initState() {
super.initState();
widget.animation.addStatusListener(_onStatus);
}
@override
void dispose() {
widget.animation.removeStatusListener(_onStatus);
super.dispose();
}If the parent can swap widget.animation, move the remove and add calls into didUpdateWidget as well.
Keeping the per-frame work small
At 60 frames per second, anything done per frame is done 60 times a second. The main costs and their fixes:
| Cost | Cause | Fix |
|---|---|---|
| Whole subtree rebuilds each frame | `addListener(() => setState(() {}))` | Use `AnimatedBuilder` or a transition widget |
| Static children rebuilt each frame | Children created inside the `builder` | Pass them as `child` and reuse them |
| Animated area repaints its neighbors | Animation shares a layer with static content | Wrap it in `RepaintBoundary` |
| Layout runs each frame | Animating `width`, `height`, or padding | Animate `Transform` or opacity when you can |
| Offscreen animations keep running | Repeating controllers on hidden pages | Rely on `TickerMode`, or call `stop()` |
Two of these deserve more explanation.
Build scope. setState in a listener rebuilds everything the State builds. AnimatedBuilder limits the rebuild to its builder function. Anything you build once and pass as child is the same widget instance on every frame, so Flutter skips it.
Layout versus paint. Changing size or padding forces layout for the widget and often its parent. Transform and Opacity change only how an already laid-out child is painted. A slide done with SlideTransition is cheaper than animating Padding, though it does not move the widget's layout position.
Opacity has one more cost. FadeTransition is cheaper than an Opacity widget rebuilt each frame, because it updates the existing render object instead of replacing the widget.
Measuring before optimizing
Do not add RepaintBoundary everywhere. Each boundary allocates its own layer, which costs memory. Use Flutter DevTools in profile mode to check frame times. The "Highlight repaints" option shows which regions repaint every frame. Add a boundary only where an animated region repaints a large static neighbor.
Exercise
A screen creates an AnimationController in initState with vsync: this and calls repeat(). The State uses SingleTickerProviderStateMixin but has no dispose method. The user navigates away and the screen is removed. What happens in a debug build, and what is the one-line fix?
Show answer
The mixin reports an error that the State was disposed with an active Ticker, and the repeating ticker is never released. Add _controller.dispose(); to a dispose override, before super.dispose().
Exercise
You write await _controller.forward(); followed by code that calls Navigator.pop. The user leaves the screen halfway through the animation. Does the code after the await run, and how do you detect the interruption?
Show answer
It does not run, because the future from a disposed controller never completes. Use await _controller.forward().orCancel; inside a try block and catch TickerCanceled to handle the interruption explicitly.
Exercise
A progress indicator calls _controller.addListener(() => setState(() {})) and its build method creates a large card with an image beside the animated bar. Which change reduces the per-frame work most?
Show answer
Replace the listener with an AnimatedBuilder (or a transition widget) that wraps only the bar. The card and image then stay outside the builder, so they are not rebuilt on each frame.