The AnimatedBuilder widget in Flutter is used to animate a portion of the UI in response to changes in an animation. It's particularly useful when you want to create custom animations or when you need more control over how a widget is animated.
Attributes:
animation (Animation):
- The animation to listen to for changes.
builder (Widget Function(BuildContext, Widget?)):
- A builder function that returns a widget tree based on the current value of the animation. It takes two arguments: the BuildContext and the child widget.
Example:
import 'package:flutter/material.dart';
class AnimatedBuilderExample extends StatefulWidget {
@override
_AnimatedBuilderExampleState createState() => _AnimatedBuilderExampleState();
}
class _AnimatedBuilderExampleState extends State<AnimatedBuilderExample> with SingleTickerProviderStateMixin {
late AnimationController _controller;
late Animation<double> _animation;
@override
void initState() {
super.initState();
_controller = AnimationController(
vsync: this,
duration: Duration(seconds: 2),
);
_animation = Tween<double>(begin: 0, end: 1).animate(_controller);
_controller.repeat(reverse: true);
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('AnimatedBuilder Widget Example'),
),
body: Center(
child: AnimatedBuilder(
animation: _animation,
builder: (context, child) {
return Transform.scale(
scale: _animation.value,
child: Container(
width: 100,
height: 100,
color: Colors.blue,
child: Center(
child: Text(
'Animated Builder',
style: TextStyle(color: Colors.white),
),
),
),
);
},
),
),
);
}
}
void main() {
runApp(MaterialApp(
home: AnimatedBuilderExample(),
));
}
Explanation:
In this example, an AnimationController is created to control the animation with a duration of 2 seconds.
A linear animation is created using Tween<double>(begin: 0, end: 1).
The _controller is set to repeat the animation indefinitely in a reverse manner.
Inside the build method, the AnimatedBuilder widget listens to changes in the animation.
The builder function is called whenever the animation value changes, allowing the transformation of a container's scale based on the animation value.
As the animation progresses, the container scales up and down smoothly, creating an animated effect.