The AnimatedBackground Class
Saving the best for last, let’s check out lib/animated-bg.dart:
At the top of the file, the
dart:math library is imported to gain access to the π constant for doing the rotational transform calculation for the spinning gear. The AnimatedBackground class constructor takes the ScrollController that will drive the rotation. The _offset property will return either the controller offset if the controller has clients (i.e. the controller is properly initialized and hooked up to an actual scrolling element like the ListView) or it will simply return zero. The build method returns an AnimatedBuilder that takes the controller (which is used as a Listenable to re-draw itself on scroll events) and builds an OverflowBox that is aligned to place the gear just off-screen.
3 place the gear in the bottom-left corner of the tested device, the iPhone Xʀ simulator. In practice, the Alignment values should be calculated from device screen height and width, to give precise values that will place the gear in the desired location (bottom-left corner, centered off to the side, etc) on any device, but for this example we’ll keep it simple.
Last up is the good part, where the animation itself takes place, within the rotate static method of the Transform class. This class takes an
angle and a
child, and rotates the child by the angle as expected. For this demo, I wanted the gear to move slowly and feel more in mesh with the scroll physics instead of the crazy freewheel effect that it had with a 1:1 value, and I wanted the gear to scroll counter-clockwise as though it were physically driving the list, so I multipled the
math.pi and then divided that product by -1024.