Sub topic 9
AnimationController
This chapter assumes you know Dart classes, mixins, closures, StatefulWidget, setState, and the build method. It also assumes basic Flutter layout.
An AnimationController is the clock for an explicit animation. It produces a value that normally moves from 0.0 to 1.0 over a chosen duration. Your widgets read that value and use it to change opacity, size, position, rotation, or another property.
Unlike an implicit animation, an explicit animation does not start just because a property changed. You decide when it starts, stops, reverses, or repeats.
Creating and using a controller
A controller belongs in a state object because it has a lifecycle. Create it in initState, and dispose of it when the state is removed. The SingleTickerProviderStateMixin supplies vsync, which lets Flutter pause the animation when the widget is not visible.
This example pulses a logo when the button is pressed. ScaleTransition reads the controller's changing value and applies it to the logo's scale.
import 'package:flutter/material.dart';
void main() {
runApp(const MaterialApp(home: PulsePage()));
}
class PulsePage extends StatefulWidget {
const PulsePage({super.key});
@override
State<PulsePage> createState() => _PulsePageState();
}
class _PulsePageState extends State<PulsePage>
with SingleTickerProviderStateMixin {
late final AnimationController _controller;
@override
void initState() {
super.initState();
_controller = AnimationController(
vsync: this,
duration: const Duration(milliseconds: 600),
);
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
void _pulse() {
_controller.forward(from: 0.0);
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: ScaleTransition(
scale: Tween<double>(begin: 1.0, end: 1.4).animate(_controller),
child: const FlutterLogo(size: 100),
),
),
floatingActionButton: FloatingActionButton(
onPressed: _pulse,
child: const Icon(Icons.play_arrow),
),
);
}
}forward() moves the controller toward 1.0. The optional from argument resets its starting value. Other useful commands include reverse(), repeat(), stop(), and reset().
The controller's value is not usually the final property value. A Tween maps the controller's range to another range. In the example, 0.0 becomes a scale of 1.0, while 1.0 becomes 1.4.
Exercise
Exercise
What does vsync: this provide, and why should the controller be disposed?
Show answer
The ticker provider supplies frame timing so Flutter can pause unnecessary work. Disposing the controller stops its ticker and releases resources when the state is removed.