The term "Animated" in Flutter generally refers to a category of widgets and classes that allow developers to create smooth and dynamic user interfaces by applying animations. One commonly used widget is AnimatedContainer. Below are details about the AnimatedContainer widget along with examples and a full code snippet.
The AnimatedContainer widget is a container that gradually changes its values over a specified duration, creating a smooth transition effect. It's useful when you want to animate changes in properties like size, color, or padding.
Attributes:
duration (Duration):
- The duration of the animation.
curve (Curve):
- The curve used for the animation. It defines the rate of change of an animation over time.
child (Widget):
- The widget contained by the AnimatedContainer.
color (Color):
- The color of the container.
width, height (double):
- The width and height of the container.
margin, padding (EdgeInsets):
- The margin and padding of the container.
Examples:
Example 1: Simple AnimatedContainer
import 'dart:math';
import 'package:flutter/material.dart';
void main() {
runApp(MaterialApp(
home: AnimatedGradientBackground(),
));
}
class AnimatedGradientBackground extends StatefulWidget {
@override
_AnimatedGradientBackgroundState createState() =>
_AnimatedGradientBackgroundState();
}
class _AnimatedGradientBackgroundState
extends State<AnimatedGradientBackground> {
Color _startColor = Colors.blue;
Color _endColor = Colors.purple;
double _borderRadius = 0.0;
void _updateColorsAndBorderRadius() {
setState(() {
_startColor = _getRandomColor();
_endColor = _getRandomColor();
_borderRadius = Random().nextDouble() * 100;
});
}
Color _getRandomColor() {
return Color.fromRGBO(
Random().nextInt(256),
Random().nextInt(256),
Random().nextInt(256),
1.0,
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: GestureDetector(
onTap: _updateColorsAndBorderRadius,
child: Center(
child: AnimatedContainer(
duration: Duration(seconds: 1),
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [_startColor, _endColor],
begin: Alignment.topLeft,
end: Alignment.bottomRight,
),
borderRadius: BorderRadius.circular(_borderRadius),
),
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Text(
'Tap to Change',
style: TextStyle(
color: Colors.white,
fontSize: 24.0,
fontWeight: FontWeight.bold,
),
),
),
),
),
),
);
}
}
This example demonstrates a simple AnimatedBox that change color and shape when tapped.