Flutter AnimationController / Tween Reuse In Multiple AnimatedBuilder

402

At the end this is what I did. I created a Stateful Widget as the Card widget, and declare the AnimatedController inside the Card widget. I then create a method in the Card widget to control the animation with its AnimatedController. In the parent widget, I'll just call the respective Card widget method to control each Card's animation.

Exposing the showCard method in Card widget:

class Card extends StatefulWidget {
  final _CardState _CardState = _CardState();
  @override
  State<StatefulWidget> createState() => _CardState;
  void showCard()=>_CardState.showCard();
}

Animation method in Card widget:

AnimationController _acCardFlip;
Animation<double> _frontFlip;
Animation<double> _backFlip;
@override
void initState() {
  super.initState();
  _acCardFlip = AnimationController(
    vsync: this,
    duration: const Duration(milliseconds: 250),
  );
  _frontFlip = Tween(
    begin: 1.0,
    end: 0.0,
  ).animate(CurvedAnimation(
    parent: _acCardFlip,
    curve: Interval(0.0, 0.5, curve: Curves.easeIn),
  ));
  _backFlip = CurvedAnimation(
    parent: _acCardFlip,
    curve: Interval(0.5, 1.0, curve: Curves.easeOut),
  );
}
showCard() {
  setState(() {
    if (_acCardFlip.isCompleted || _acCardFlip.velocity > 0)
      _acCardFlip.reverse();
    else
      _acCardFlip.forward();
  });
}

In the parent widget, just create the Card widget and call the method to animate:

Card card = Card();
card.showCard();

Then just create the Card in a list to control multiple cards independently.

Share:
402
Author by

Zane

Updated on December 11, 2022

Comments

  • Zane less than a minute

    I'm building a screen with multiple cards, upon tapping on one of the card, the card should flip. I've no problem animating the card using AnimatedController with Tweens and AnimatedBuilder. My question is what is the best way to reuse/apply the same AnimatedController in all my 'Card' widget without having to create multiple AnimatedControllers and Tweens and set it to each card, but still allow me to separately animate them.