Welcome to the exciting world of animations in Flutter! In this chapter, we'll explore how to make your apps dynamic and engaging. A fundamental concept in Flutter animation is understanding the difference between implicit and explicit animations. This distinction will guide you in choosing the right approach for your animation needs.
Implicit animations are the simpler of the two. They are declarative and handle the animation process behind the scenes. You simply define the start and end states of a widget's properties, and Flutter interpolates the changes over time. These are ideal for straightforward property changes like color fades, size adjustments, or position shifts.
Think of implicit animations as 'set it and forget it'. You tell Flutter what you want the widget to look like at a certain point, and it animates the transition from its current state to that new state. No explicit animation controllers or explicit timelines are needed.
AnimatedContainer(
duration: const Duration(seconds: 1),
width: 200.0,
height: 200.0,
color: Colors.blue,
alignment: Alignment.center,
child: const Text('Hello'),
)In the example above, changing any property of AnimatedContainer (like width, height, color, or alignment) will automatically trigger an animation over the specified duration. Flutter manages the interpolation of these properties for you.
Explicit animations, on the other hand, give you much more control. They involve explicitly defining and managing animation controllers, Tweens, and curves. This approach is necessary when you need complex animation sequences, control over the animation's progress, or the ability to pause, reverse, or repeat animations.
With explicit animations, you are the choreographer. You define every step of the animation, from its start and end values to the timing and easing functions. This offers immense flexibility but requires a deeper understanding of the animation system.
class MyExplicitAnimation extends StatefulWidget {
@override
_MyExplicitAnimationState createState() => _MyExplicitAnimationState();
}
class _MyExplicitAnimationState extends State<MyExplicitAnimation> with SingleTickerProviderStateMixin {
late AnimationController _controller;
late Animation<double> _animation;
@override
void initState() {
super.initState();
_controller = AnimationController(
duration: const Duration(seconds: 2),
vsync: this,
);
_animation = CurvedAnimation(parent: _controller, curve: Curves.easeIn);
_controller.forward(); // Start the animation
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return FadeTransition(
opacity: _animation,
child: const FlutterLogo(size: 100),
);
}
}