From my point of view, all animations continuously render the widget with some often-changed value. For example, a spinning hand on a clock has a value called 'angle' to indicate its position.
In Flutter, it seems that StatefulWidget is enough for it. My question is:
- What functions do
AnimatedBuilder/AnimatedWidgethave? - What are the differences between
AnimatedBuilder/AnimatedWidgetandStatefulWidget?
CodePudding user response:
I'll assume that AnimationBuilder is AnimatedBuilder because there is no such class as AnimationBuilder in the Flutter SDK.
Short answer
There are no differences besides the class names and the parameters.
Long answer
In Flutter, it seems that StatefulWidget is enough for it.
You are right.
What functions do
AnimatedBuilder/AnimatedWidgethave?
Nothing special, they are classes that exists only to wrap common/boilerplate code, see:
AnimatedWidget: flutter/lib/src/widgets/transitions.dart is simply a StatefulWidget that takes a listenable and triggers thesetStatewhenever the listanable notifies a change.- The
AnimatedBuilder: flutter/lib/src/widgets/transitions.dart is a subclass ofListenableBuilderwhich is a subclass ofAnimatedWidget(!), the only difference is thatAnimatedBuilderuses your callback as thebuildmethod ofAnimatedWidget.
That being said, lets go to the code:
AnimatedBuilderis simply aStatefulWidgetthat uses your callback function (builder: (...) { }) as build method. It also triggerssetStateeverytime the Listenable (animation) notifies a change.
Widget build(BuildContext context) {
return Center( // The [Center] widget instance will not rebuild.
child: AnimatedBuilder(
animation: animation,
builder: (context, child) {
return /* Widge tree that will rebuild when [animation] changes. */;
},
),
);
}
- The equivalent code using
AnimatedWidgetis:
Widget build(BuildContext context) {
return Center( // The [Center] widget instance will not rebuild.
child: MyAnimatedWidget(animation: animation),
);
}
// ...
class MyAnimatedWidget extends AnimatedWidget {
const MyAnimatedWidget({required Listenable animation}) : super(listenable: animation);
Widget build(BuildContext context) {
return /* Widge tree that will rebuild when [animation] changes. */;
}
}
What are the differences between AnimatedBuilder/AnimatedWidget and StatefulWidget?
As I said, there is no semantic or real difference. AnimatedWidget and AnimatedBuilder are only abstractions of StatefulWidget.
