Flutter Animations
Animations bring your app to life. Flutter gives you powerful tools to create smooth, natural motion. The core building blocks are AnimationController, Tween, and AnimatedBuilder.
Here's a basic fade-in animation:
class FadeInDemo extends StatefulWidget {
const FadeInDemo({super.key});
@override
State<FadeInDemo> createState() => _FadeInDemoState();
}
class _FadeInDemoState extends State<FadeInDemo>
with SingleTickerProviderStateMixin {
late AnimationController _controller;
late Animation<double> _fadeAnimation;
@override
void initState() {
super.initState();
_controller = AnimationController(
vsync: this,
duration: const Duration(milliseconds: 1000),
);
_fadeAnimation = Tween<double>(begin: 0.0, end: 1.0).animate(
CurvedAnimation(parent: _controller, curve: Curves.easeInOut),
);
_controller.forward();
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return FadeTransition(
opacity: _fadeAnimation,
child: const Text('Hello, Flutter!'),
);
}
}
A Tween defines the start and end values. A Curve controls the rate of change โ Curves.easeInOut starts and ends slowly for a natural feel.
For a slide animation:
// In initState
_slideAnimation = Tween<Offset>(
begin: const Offset(-1.0, 0.0),
end: Offset.zero,
).animate(
CurvedAnimation(parent: _controller, curve: Curves.elasticOut),
);
// In build
SlideTransition(
position: _slideAnimation,
child: const Text('Slide me in!'),
);
Scale animations work the same way:
// In initState
_scaleAnimation = Tween<double>(begin: 0.0, end: 1.0).animate(
CurvedAnimation(parent: _controller, curve: Curves.bounceOut),
);
// In build
ScaleTransition(
scale: _scaleAnimation,
child: const Text('Bounce!'),
);
The AnimatedBuilder widget lets you animate any property without creating a separate widget:
AnimatedBuilder(
animation: _controller,
builder: (context, child) {
return Transform.rotate(
angle: _controller.value * 3.14159,
child: child,
);
},
child: const Icon(Icons.refresh, size: 48),
);
Combine animations for complex effects โ fade and slide together for a polished entrance:
FadeTransition(
opacity: _fadeAnimation,
child: SlideTransition(
position: _slideAnimation,
child: const Text('Combined!'),
),
);
Always remember to call dispose() on your animation controller to free resources.