import 'package:flutter/material.dart';
class SimpleAnimationScreen extends StatefulWidget {
@override
State<SimpleAnimationScreen> createState() => _SimpleAnimationScreenState();
}
class _SimpleAnimationScreenState extends State<SimpleAnimationScreen> with SingleTickerProviderStateMixin {
late AnimationController _controller;
late Animation<double> _sizeAnimation;
@override
void initState() {
super.initState();
_controller = AnimationController(
vsync: this,
duration: const Duration(seconds: 2),
);
_sizeAnimation = Tween<double>(begin: 100, end: 200).animate(_controller);
_controller.addStatusListener((status) {
if (status == AnimationStatus.completed) {
_controller.reverse();
} else if (status == AnimationStatus.dismissed) {
_controller.forward();
}
});
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Simple Animation Screen')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
AnimatedBuilder(
animation: _sizeAnimation,
builder: (context, child) {
return Container(
width: _sizeAnimation.value,
height: _sizeAnimation.value,
color: Colors.blue,
);
},
),
const SizedBox(height: 40),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
onPressed: () {
_controller.forward();
},
child: const Text('Start Animation'),
),
const SizedBox(width: 20),
ElevatedButton(
onPressed: () {
_controller.stop();
},
child: const Text('Stop'),
),
],
),
],
),
),
);
}
}
We use AnimationController to control the animation timing. The controller runs for 2 seconds. We create a Tween that changes the size from 100 to 200 pixels. The AnimatedBuilder rebuilds the square container whenever the animation value changes, updating its width and height.
We listen to the animation status to make it reverse direction when it finishes growing, and forward again when it finishes shrinking. This creates a smooth back-and-forth effect.
The 'Start Animation' button calls _controller.forward() to begin the animation. The 'Stop' button calls _controller.stop() to pause it.
This example shows how to use AnimationController simply and clearly to animate a widget's size.