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
/AnimatedWidget
have? - What are the differences between
AnimatedBuilder
/AnimatedWidget
andStatefulWidget
?
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
/AnimatedWidget
have?
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 thesetState
whenever the listanable notifies a change.- The
AnimatedBuilder
: flutter/lib/src/widgets/transitions.dart is a subclass ofListenableBuilder
which is a subclass ofAnimatedWidget
(!), the only difference is thatAnimatedBuilder
uses your callback as thebuild
method ofAnimatedWidget
.
That being said, lets go to the code:
AnimatedBuilder
is simply aStatefulWidget
that uses your callback function (builder: (...) { }
) as build method. It also triggerssetState
everytime 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
AnimatedWidget
is:
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
.