Liu Silong
Liu Silong

Reputation: 5532

AnimatedWidget and AnimatedBuilder in Flutter

Hi everyone ,I have a problem, I don’t understand the difference between AnimatedWidget and AnimatedBuilder. The comments in the source code are as follows:

AnimatedWidget:

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

AnimatedBuilder:

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

I want to know how to choose between them, because I don't quite understand the documentation, thanks!

Upvotes: 4

Views: 4055

Answers (2)

SanjaySingh
SanjaySingh

Reputation: 1867

Both the animatedWidget and animatedBuilder do the same work related to the animations.

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.

The clear cut difference between then is :

  • AnimatedWidget only takes animation as a parameter whereas AnimatedBuilder takes two arguments "child" and "animation".

  • AnimatedWidget is implemented as a class extending AnimatedWidget. E.g.

class abc extends AnimatedWidget

Whereas AnimatedBuilder is implemented as a widget inside a class. E.g.

child : AnimatedBuilder( .....),

Now, although both do the same work but both have different ways of doing it. In AnimatedWidget it has its own child so we have to pass only the animation.whereas in AnimatedBuilder we need to pass both child and animation.

Take AnimatedWidget for example u can use the same AnimatedWidget class for any number of animations with different values.

Now you will be thinking that if AnimatedWidget can do the thing why we need AnimatedBuilder?

The answer is simple

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.

Upvotes: 2

Rémi Rousselet
Rémi Rousselet

Reputation: 277707

There's no real difference between them besides the syntax needed to use it.

To be clear, this is the code of 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);
  }
}

...Yup, does nothing

From this code we can clearly see that AnimatedBuilder is just a different syntax of using AnimatedWidget. Since AnimatedBuilder is an AnimatedWidget that delegate all the layout logic to a callback

So in the end, it's really up to you. Both do the same thing. Use what makes it more readable for you

Upvotes: 8

Related Questions