一、什么是AnimatedBuilder?
AnimatedBuilder 是用于构建动画的统一widget,AnimatedBuilder对于希望将动画作为更大构建函数的一部分包含在内的更复杂的widget时非常有用,其实你可以这样理解:AnimatedBuilder是拆分动画的一个工具类,借助它我们可以将动画和widget进行分离:
在上面的实例中我们的代码存在一个问题:更改动画需要更改显示logo的widget。更好的解决方案是将职责分离:
-显示logo
-定义Animation对象
-渲染过渡效果
接下来借助AnimatedBuilder来完成此分离。AnimatedBuilder是渲染树种的一个独立的类,与AnimatedWidget类似,AnimatedBuilder自动监听来自Animatiion对象的通知,不需要手动调用addListener()
我们根据下图的widget树来创建我们的代码:
二、
import 'package:flutter/material.dart';
import 'package:flutter_color_plugin/flutter_color_plugin.dart';
void main() => runApp(LogoApp());
class LogoApp extends StatefulWidget {
@override
_LogoAppState createState() => _LogoAppState();
}
class LogoWidget extends StatelessWidget{
@override
Widget build(BuildContext context) {
return Container(
margin: EdgeInsets.symmetric(vertical: 10),
child: FlutterLogo(),
);
}
}
class GrowTransition extends StatelessWidget{
GrowTransition({this.child,this.animation});
final Widget child;
final Animation<double> animation;
@override
Widget build(BuildContext context) =>Center(
child: AnimatedBuilder(
animation: animation,
builder: (context,child)=>Container(
height: animation.value,
width: animation.value,
child: child,
),
child: child,
),
);
}
class _LogoAppState extends State<LogoApp> with SingleTickerProviderStateMixin{
Animation<double> animation;
AnimationController controller;
@override
void initState() {
super.initState();
controller=AnimationController(vsync: this,duration: Duration(seconds: 12));
animation=Tween<double>(begin: 0,end: 300).animate(controller);
controller.forward();
}
@override
void dispose() {
controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return GrowTransition(animation: animation,child: LogoWidget());
}
}
运行结果:
也可以从小放大
和以前的不同:
1、构造了要给继承自StatelessWidget的一个类,这个类里面使用了AnimationBuilder。
2、AnimationBuilder里面接收了一个animation,然后AnimatedBuilder会自动监听animation的变化,然后来渲染我们的动画,也就是可以将GrowTransitiion当成一个wrapper,它wrapper我们这个child,也就是wrap我们的child widget,来使child widget有这样一个动画效果。
这样就可以将动画执行过程和child的具体业务逻辑进行分离。