Sub topic 10
Tickers and vsync
This chapter assumes you know Dart mixins, StatefulWidget lifecycle methods (initState, dispose), and the AnimationController basics from the previous chapter. It explains what the vsync: this argument means, why it needs a mixin, and which errors come from getting it wrong.
What a Ticker is
A Ticker is an object that calls a function once per frame while it is active. Each call receives the time elapsed since the ticker started, as a Duration. Flutter's scheduler decides when frames happen, and a ticker asks the scheduler to call it back at the start of each frame.
An AnimationController has no clock of its own. It owns one ticker. On each tick it converts the elapsed time into a value between lowerBound and upperBound (0.0 to 1.0 by default), then notifies its listeners. Widgets such as AnimatedBuilder and FadeTransition listen to the controller and rebuild or repaint.
What vsync means
Vsync is short for vertical synchronization. The display refreshes at a fixed rate, for example 60 or 120 times per second. The engine signals the start of each frame, and tickers fire in response. An animation advances once per displayed frame, with no timers and no wasted work between frames.
The vsync parameter of AnimationController has the type TickerProvider. A TickerProvider has one method, createTicker, and the controller calls it to get its ticker. Passing vsync: this means "this State object creates my ticker."
Why the State provides it
The State object is a good ticker provider because it knows when the widget is part of the tree. Flutter's ticker mixins use that to do two things:
- Mute tickers for hidden subtrees. The mixins look up the nearest
TickerModeancestor. WhenTickerMode.enabledisfalse, the tickers are muted. The clock keeps running, but no frame callbacks reach your controller. Navigator uses this for routes that are fully covered by another route, so a hidden screen does not burn CPU. - Catch leaks. In debug mode, when the
Stateis disposed while a ticker is still active, Flutter throws an error. The message begins "A Ticker was active when the State itself was disposed."
Choosing the mixin
| Mixin | Tickers allowed | Use when |
|---|---|---|
| `SingleTickerProviderStateMixin` | One | The state owns exactly one controller. |
| `TickerProviderStateMixin` | Any number | The state owns several controllers, or creates them later. |
SingleTickerProviderStateMixin is slightly cheaper because it tracks a single ticker. If you ask it for a second ticker, a debug assertion fails. The message says the SingleTickerProviderStateMixin is being used for multiple tickers and suggests TickerProviderStateMixin.
Both mixins require on State<T>, so you can only apply them to a State subclass. A StatelessWidget cannot be a TickerProvider. That is one reason explicit animations live in stateful widgets.
Example: two controllers
This state owns two controllers, so it needs TickerProviderStateMixin. Tapping the text fades it in and out. The icon rotates continuously.
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: Scaffold(body: Center(child: TwoControllers()))));
class TwoControllers extends StatefulWidget {
const TwoControllers({super.key});
@override
State<TwoControllers> createState() => _TwoControllersState();
}
class _TwoControllersState extends State<TwoControllers>
with TickerProviderStateMixin {
late final AnimationController _fade;
late final AnimationController _spin;
@override
void initState() {
super.initState();
_fade = AnimationController(
vsync: this,
duration: const Duration(milliseconds: 300),
value: 1.0,
);
_spin = AnimationController(
vsync: this,
duration: const Duration(seconds: 2),
)..repeat();
}
@override
void dispose() {
_fade.dispose();
_spin.dispose();
super.dispose();
}
void _toggle() {
if (_fade.status == AnimationStatus.completed ||
_fade.status == AnimationStatus.forward) {
_fade.reverse();
} else {
_fade.forward();
}
}
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: _toggle,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
RotationTransition(
turns: _spin,
child: const Icon(Icons.sync, size: 48),
),
FadeTransition(
opacity: _fade,
child: const Text('Tap to fade'),
),
],
),
);
}
}Order matters in dispose. Dispose the controllers first, then call super.dispose(). The mixin checks for active tickers inside its own dispose, so a controller still running at that point triggers the error.
Using a Ticker directly
You rarely need a bare Ticker, but it shows what a controller does internally. This widget displays elapsed seconds and updates on every frame.
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
class ElapsedText extends StatefulWidget {
const ElapsedText({super.key});
@override
State<ElapsedText> createState() => _ElapsedTextState();
}
class _ElapsedTextState extends State<ElapsedText>
with SingleTickerProviderStateMixin {
late final Ticker _ticker;
Duration _elapsed = Duration.zero;
@override
void initState() {
super.initState();
_ticker = createTicker((elapsed) {
setState(() => _elapsed = elapsed);
})..start();
}
@override
void dispose() {
_ticker.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final seconds = _elapsed.inMilliseconds / 1000;
return Text('${seconds.toStringAsFixed(1)} s');
}
}The createTicker method comes from the mixin. The ticker runs until you stop or dispose it, with no duration and no end value. An AnimationController adds the bounded value, the status, and forward/reverse/repeat on top of this loop.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| Assertion about multiple tickers | A second controller on `SingleTickerProviderStateMixin` | Switch to `TickerProviderStateMixin`. |
| "A Ticker was active when the State itself was disposed" | The controller was not disposed, or it was disposed after `super.dispose()` | Call `controller.dispose()` before `super.dispose()`. |
| "Ticker used after being disposed" | A callback or `Future` still drives the controller after `dispose` | Check `mounted` before calling `forward()` after an `await`. |
| Compile error on `vsync: this` | The class has no ticker mixin, or it is not a `State` | Add the mixin to the `State` class. |
| Animation never advances in a hidden tab | An ancestor `TickerMode` has `enabled: false` | This is intended. It resumes when the subtree is visible again. |
Tickers in tests
Widget tests run on a fake clock, so tickers do not advance by themselves. Call await tester.pump(const Duration(milliseconds: 100)) to move the clock forward by a fixed amount. pumpAndSettle() keeps pumping until no frames are scheduled. It never finishes if a controller calls repeat(), so use fixed pump durations for repeating animations.
Key points
- A
Tickercalls a function once per frame, and anAnimationControllerturns those calls into a value. vsync: thishands the controller aTickerProvider, which is yourStateobject through a mixin.- Use
SingleTickerProviderStateMixinfor one controller andTickerProviderStateMixinfor more. TickerModemutes tickers in hidden subtrees, which saves work without any code from you.- Dispose controllers before calling
super.dispose().
Exercise
A State class uses SingleTickerProviderStateMixin and creates one AnimationController in initState. You later add a second controller for a fade effect, and the app now fails an assertion in debug mode on startup. What two changes fix the problem, and in what order should the two controllers be disposed relative to super.dispose()?
Show answer
Replace SingleTickerProviderStateMixin with TickerProviderStateMixin, because the single-ticker mixin allows only one ticker. Also make sure dispose() disposes both controllers. Both dispose calls go before super.dispose(), since the mixin checks for active tickers inside its own dispose.
Exercise
Why does pumpAndSettle() never return in a widget test for a widget whose controller calls repeat(), and what do you use instead?
Show answer
A repeating controller keeps scheduling a frame on every tick, so the test never reaches a state with no pending frames. Use tester.pump(Duration) with a fixed duration to advance the fake clock by a known amount, then check the widget.