import 'package:flutter/material.dart';
class StaggeredAnimationDemo extends StatefulWidget {
@override
_StaggeredAnimationDemoState createState() => _StaggeredAnimationDemoState();
}
class _StaggeredAnimationDemoState extends State<StaggeredAnimationDemo> with SingleTickerProviderStateMixin {
late AnimationController _controller;
late Animation<double> _positionAnimation;
late Animation<Color?> _colorAnimation;
late Animation<double> _sizeAnimation;
@override
void initState() {
super.initState();
_controller = AnimationController(
duration: const Duration(seconds: 6),
vsync: this,
);
_positionAnimation = Tween<double>(begin: -100, end: 100).animate(
CurvedAnimation(
parent: _controller,
curve: const Interval(0.0, 0.33, curve: Curves.easeInOut),
),
);
_colorAnimation = ColorTween(begin: Colors.blue, end: Colors.red).animate(
CurvedAnimation(
parent: _controller,
curve: const Interval(0.34, 0.66, curve: Curves.easeInOut),
),
);
_sizeAnimation = Tween<double>(begin: 100, end: 200).animate(
CurvedAnimation(
parent: _controller,
curve: const Interval(0.67, 1.0, curve: Curves.easeInOut),
),
);
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
void _startAnimation() {
_controller.reset();
_controller.forward();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Staggered Animation Demo')),
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
AnimatedBuilder(
animation: _controller,
builder: (context, child) {
return Transform.translate(
offset: Offset(_positionAnimation.value, 0),
child: Container(
width: _sizeAnimation.value,
height: _sizeAnimation.value,
color: _colorAnimation.value,
),
);
},
),
const SizedBox(height: 40),
ElevatedButton(
onPressed: _startAnimation,
child: const Text('Start Animation'),
),
],
),
),
);
}
}
We use a single AnimationController with a 6-second duration to control all animations.
Three animations are created with Tween and ColorTween, each assigned a part of the total duration using Interval:
- Position: Moves the box horizontally from -100 to 100 pixels in the first third (0.0 to 0.33).
- Color: Changes from blue to red in the middle third (0.34 to 0.66).
- Size: Grows from 100 to 200 pixels in the last third (0.67 to 1.0).
The AnimatedBuilder rebuilds the box whenever the controller ticks, applying the current animation values for position, color, and size.
The _startAnimation method resets and starts the controller to run the staggered animations in sequence.