Sub topic 10
Tickers and `vsync`
This chapter assumes you know Dart classes, mixins, generics, closures, Flutter’s build method, and the difference between StatefulWidget and StatelessWidget. You should also know how setState works.
An AnimationController changes its value over time. It needs a clock to know when to produce the next value. In Flutter, that clock is a ticker.
A ticker calls a callback once for each animation frame while it is active. The controller listens to those callbacks, updates its value from 0.0 to 1.0, and notifies widgets such as AnimatedBuilder or FadeTransition.
What `vsync` does
vsync means vertical synchronization. It connects an animation to a TickerProvider, usually the State object that owns the animation.
The provider lets Flutter coordinate the ticker with the display’s frame schedule. It also allows Flutter to mute the ticker when the widget’s subtree is disabled by mechanisms such as TickerMode. This avoids producing animation frames that cannot be shown.
The SingleTickerProviderStateMixin adds a TickerProvider implementation to a State object:
import 'package:flutter/material.dart';
class PulseLogo extends StatefulWidget {
const PulseLogo({super.key});
@override
State<PulseLogo> createState() => _PulseLogoState();
}
class _PulseLogoState extends State<PulseLogo>
with SingleTickerProviderStateMixin {
late final AnimationController _controller;
@override
void initState() {
super.initState();
_controller = AnimationController(
vsync: this,
duration: const Duration(seconds: 1),
)..repeat(reverse: true);
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return ScaleTransition(
scale: Tween<double>(begin: 0.8, end: 1.2).animate(_controller),
child: const FlutterLogo(size: 80),
);
}
}Here, this is the State object, and the mixin makes it a valid ticker provider. The controller starts at 0.0, moves to 1.0, then reverses because repeat(reverse: true) was used.
Choosing a ticker provider
Use SingleTickerProviderStateMixin when the state owns one controller. Use TickerProviderStateMixin when the state owns multiple controllers:
class _ScreenState extends State<Screen>
with TickerProviderStateMixin {
late final AnimationController first;
late final AnimationController second;
}Both controllers can use vsync: this. Each controller still needs to be disposed.
Exercise
Which mixin should you normally use for one AnimationController, and what must you do when the widget is disposed?
Show answer
Use SingleTickerProviderStateMixin and call _controller.dispose() in dispose.