Animations make your app more lively and engaging by adding movement and transitions to UI elements. Flutter provides powerful tools to create smooth animations easily.
Let's animate a simple fade effect where a widget changes its opacity smoothly.
// Import necessary Flutter packages
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: FadeDemo(),
);
}
}
// StatefulWidget needed because animation changes over time
class FadeDemo extends StatefulWidget {
@override
_FadeDemoState createState() => _FadeDemoState();
}
class _FadeDemoState extends State with SingleTickerProviderStateMixin {
late AnimationController _controller;
late Animation _animation;
@override
void initState() {
super.initState();
// Create AnimationController with 2 seconds duration
_controller = AnimationController(
duration: const Duration(seconds: 2),
vsync: this,
);
// Define tween animation from 0 (invisible) to 1 (fully visible)
_animation = Tween(begin: 0, end: 1).animate(_controller);
// Start the animation forward
_controller.forward();
}
@override
void dispose() {
_controller.dispose(); // Dispose controller to free resources
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Fade Animation Example')),
body: Center(
child: FadeTransition(
opacity: _animation,
child: Container(
width: 200,
height: 200,
color: Colors.blue,
child: Center(
child: Text(
'Hello Flutter!',
style: TextStyle(color: Colors.white, fontSize: 24),
),
),
),
),
),
);
}
}
AnimationController controls the animation duration and progress.Tween defines the range of animation values (opacity 0 to 1).FadeTransition widget applies the opacity animation to its child.SingleTickerProviderStateMixin provides the ticker needed for animation updates.StatefulWidget because animation changes over time and UI must update.StatelessWidget does not change its appearance after being built. Use it for static UI.
StatefulWidget allows UI to update dynamically, necessary for animations, user input, or data changes.
Imagine a curtain slowly opening on a stage. The AnimationController is like the person pulling the curtain at a steady speed, and the Tween is the path the curtain travels from closed to fully open.
To dive deeper, visit the official Flutter animation docs: Flutter Animations.