import 'package:flutter/material.dart';
import 'dart:math';
class AnimatedBoxScreen extends StatefulWidget {
@override
State<AnimatedBoxScreen> createState() => _AnimatedBoxScreenState();
}
class _AnimatedBoxScreenState extends State<AnimatedBoxScreen> {
double boxSize = 100;
Color boxColor = Colors.blue;
double boxOpacity = 1.0;
final Random random = Random();
void changeAnimation() {
setState(() {
boxSize = 50 + random.nextInt(151).toDouble(); // 50 to 200
boxColor = Color.fromARGB(
255,
random.nextInt(256),
random.nextInt(256),
random.nextInt(256),
);
boxOpacity = 0.3 + random.nextDouble() * 0.7; // 0.3 to 1.0
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Animated Box Screen')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
AnimatedOpacity(
duration: Duration(seconds: 1),
opacity: boxOpacity,
child: AnimatedContainer(
width: boxSize,
height: boxSize,
color: boxColor,
duration: Duration(seconds: 1),
curve: Curves.easeInOut,
),
),
SizedBox(height: 20),
ElevatedButton(
onPressed: changeAnimation,
child: Text('Change Animation'),
),
],
),
),
);
}
}
We use AnimatedContainer to smoothly animate the box's size and color changes over 1 second. The AnimatedOpacity widget wraps the container to animate the opacity changes simultaneously. When the button is pressed, changeAnimation() generates new random values for size, color, and opacity, then calls setState() to update the UI. The animations run together smoothly because both widgets have the same duration.
This approach shows how Flutter's implicit animations let you animate properties easily without managing animation controllers.