Flutter Widget 之AnimatedBuilder

661 阅读1分钟

Flutter的动画框架为您提供了很多选项,可以轻松的为widget设置动画。

一个很棒的选择是AnimatedBuilder widget。

使用AnimatedBuilder很简单。

首先,我们给它一个动画,

在这里,我们使用的是Tween。

这个动画会360度原地打转。

final animation = Tween(begin: 0,
    end: 2 * pi).animate(controller);
AnimatedBuilder(
    animation: animation,    
);

给它一个会返回动画widget的构建器(builder)。在这里,我们使用旋转变化(rotate transform)来创建旋转效果。

你可以为AnimatedBuilder提供一个独立于动画存在的可选子项,允许AnimatedBuilder优化其渲染。

final animation = Tween(begin: 0,
    end: 2 * pi).animate(controller);
AnimatedBuilder(
    animation: animation, 
    child: FlutterLogo(),
    builder: (context, builder){
        return Transform.rotate(
            angle: animation.value,
            child: Container(),    
        );
    },
);

如果您想知道哪个动画控制器的来源,它是完全取决于你的。

AnimationController controller;

一个建议是将代码包装在Stateful widget中的构建函数中,并筒鼓widget的状态管理控制器。

Stateful Widget

AnimationController controller;

@override
void initState(){
    supter.initState();
    controller = AnimationController(
        duration: const Duration(
            second: 4,
        ),
        vsync: this,
    )..repeat();
}

如果想了解有关AnimatedBuilder的内容,或者关于Flutter的其他功能,请访问flutter.io

原文翻译自视频:视频地址