Flutter 中的 AnimatedWidget 和 AnimatedBuilder

AnimatedWidget and AnimatedBuilder in Flutter

大家好 ,我有个问题,我不明白AnimatedWidgetAnimatedBuilder的区别。源码中注释如下:

动画小部件:

/// For more complex case involving additional state, consider using
/// [AnimatedBuilder].

动画生成器:

/// For simple cases without additional state, consider using
/// [AnimatedWidget].

我想知道如何选择它们,因为我不太了解文档,谢谢!

除了使用它所需的语法之外,它们之间没有真正的区别。

要清楚,这是AnimatedBuilder的代码:

class AnimatedBuilder extends AnimatedWidget {
  const AnimatedBuilder({
    Key key,
    @required Listenable animation,
    @required this.builder,
    this.child,
  }) : assert(builder != null),
      super(key: key, listenable: animation);

  final TransitionBuilder builder;
  final Widget child;

  @override
  Widget build(BuildContext context) {
    return builder(context, child);
  }
}

...是的,什么都不做

从这段代码中我们可以清楚地看到AnimatedBuilder只是使用AnimatedWidget的不同语法。由于 AnimatedBuilder 是一个 AnimatedWidget,它将所有布局逻辑委托给回调

所以最后,这真的取决于你。两者做同样的事情。使用使它更易读的内容

animatedWidgetanimatedBuilder 都做与动画相关的相同工作。

before moving on u must know that to create an animation we must require atleast two things 1. The animation itself and 2. The widget on which we are going to apply the animation.

明确的两者的区别是:

  • AnimatedWidget 仅将动画作为参数,而 AnimatedBuilder 有两个参数 "child" 和 "animation".

  • AnimatedWidget 实现为 class 扩展 AnimatedWidget。 例如

class abc extends AnimatedWidget

AnimatedBuilder 是作为 class 中的小部件实现的。 例如

child : AnimatedBuilder( .....),

现在,虽然两者做同样的工作,但做事的方式不同。在 AnimatedWidget 中它有自己的 child 所以我们只需要传递 AnimatedBuilder 中的 animation.whereas 我们需要同时传递 child 和 animation.

AnimatedWidget 为例,您可以对具有不同值的任意数量的动画使用相同的 AnimatedWidget class。

现在你会想,如果 AnimatedWidget 可以做我们为什么需要 AnimatedBuilder 的事情?

答案很简单

Changing the animation in AnimatedWidget requires changing the widget that renders the logo or our child. So what AnimatedBuilder did is to provided a choice to is to pass both child of your choice and animation explicitly.