AnimatedBuilder is useful for more complex widgets that wish to include an animation as part of a larger build function. To use AnimatedBuilder, simply construct the widget and pass it a builder function.
AnimatedBuilder 对于要把animation作为build函数的一部分的较为复杂的widget很有用。 想要使用 AnimatedBuilder,只需构造widget并将其传递给builder函数。
If your builder function contains a subtree that does not depend on the animation, it’s more efficient to build that subtree once instead of rebuilding it on every animation tick.
如果你的builder函数包含不依赖于animation的子树,则只build这子树一次要比在每个animation tick时都rebuild它更有效。
If you pass the pre-built subtree as the child parameter, the AnimatedBuilder will pass it back to your builder function so that you can incorporate it into your build.
如果你将pre-built的子树作为child参数传递,AnimatedBuilder 会将该子树传递回给你的builder函数,以便你可以将该子树合并到你的build中。
Using this pre-built child is entirely optional, but can improve performance significantly in some cases and is therefore a good practice.
使用这个pre-built child完全是可选的,但在某些情况下可以显着提高性能,因为这是一个很好的做法。
This code defines a widget that spins a green square continually. It is built with an AnimatedBuilder and makes use of the child feature to avoid having to rebuild the Container each time.
这段代码定义了一个持续旋转绿色方块的widget。 它是使用 AnimatedBuilder 构建的,并利用child来避免每次都重新构建Container。
class MyStatefulWidget extends StatefulWidget {
const MyStatefulWidget({Key? key}) : super(key: key);
@override
State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}
/// AnimationControllers can be created with `vsync: this` because of TickerProviderStateMixin.
class _MyStatefulWidgetState extends State<MyStatefulWidget>
with TickerProviderStateMixin {
late final AnimationController _controller = AnimationController(
duration: const Duration(seconds: 10),
vsync: this,
)..repeat();
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return AnimatedBuilder(
animation: _controller,
child: Container(
width: 200.0,
height: 200.0,
color: Colors.green,
child: const Center(
child: Text('Whee!'),
),
),
builder: (BuildContext context, Widget? child) {
return Transform.rotate(
angle: _controller.value * 2.0 * math.pi,
child: child,
);
},
);
}
}