Flutter
AnimatedBuilder
Rebuild UI each frame with AnimatedBuilder.
What is AnimatedBuilder?
AnimatedBuilder is a widget that listens to an Animation and rebuilds the UI on every frame. You pass the Animation object to the animation parameter and a function taking (context, child) to the builder parameter.
AnimatedBuilder(
animation: animasyon,
builder: (context, child) {
return Container(width: animasyon.value);
},
)
This widget calls builder again every time the animation updates.
The animation and builder parameters
The animation parameter takes an Animation<double> object. The builder is a function with the signature (BuildContext context, Widget? child); it is called on every frame and returns a Widget. The child parameter is used to efficiently pass child widgets that do not change between frames.
AnimatedBuilder(
animation: animasyon,
builder: (context, child) {
return Opacity(opacity: animasyon.value, child: child);
},
child: const Text('Selam'),
)
Exercise Use AnimatedBuilder
Define a StatelessWidget named Ornek with a required final Animation<double> animasyon field. Its build method should return an AnimatedBuilder with animation set to animasyon and builder returning a Container. Print 'hazir' in main.
Show example solution
import 'package:flutter/material.dart';
class Ornek extends StatelessWidget {
final Animation<double> animasyon;
const Ornek({super.key, required this.animasyon});
@override
Widget build(BuildContext context) {
return AnimatedBuilder(
animation: animasyon,
builder: (context, child) {
return Container();
},
);
}
}
void main() {
print('hazir');
}
Test yourself
-
What object does AnimatedBuilder listen to?
- Tween
- Future
- Animation
- Stream
Show answer
Animation — AnimatedBuilder listens to an Animation object and calls builder on every update. Future and Stream are for async operations, and Tween is a value transition class; AnimatedBuilder does not listen to these.
-
The builder parameter
AnimatedBuilder(
animation: animasyon,
____: (context, child) {
return Container();
},
)
Show answer
AnimatedBuilder(
animation: animasyon,
builder: (context, child) {
return Container();
},
)
-
AnimatedBuilder parts
- animation
- The Animation being listened to
- builder
- Function called on every frame
- context
- Build context
- child
- Static child widget
Next lesson: Curve