Search code examples
animationflutterticker

AnimationController: Can we pass the TickerProvider vsync to an other class?


I develop an application in Flutter with a lot of animations quite varied. I would like to structure my code by separating views, logic (model BLoC) and ANIMATIONS. For this problem I try to declare several times the same animation for buttons in a different class of my StatefulWidget.

However, I am stuck because I have to pass a TickerProvider to my animation class, and I do not do it the right way.

Constructor animation class

AppBloc(TickerProvider tickerProvider) {
    banimationController = AnimationController(
      vsync: tickerProvider,
      duration: Duration(milliseconds: 100),
      lowerBound: 0,
      upperBound: 0.05,
    );
}

Declaration

AppBloc(this);

I know this is probably not the right way, I wrote this code to illustrate my problem.

I just want to separate my animations declarations in an other file.


Solution

  • TickerProvider is a mixin. You can use multiple mixins in a class using with keyword. The best way to use the mixin uff TickerProvider is using it with with keyword.

    Example :

      class _HomeState extends State<Home> with TickerProviderStateMixin {
      Animation<double> _animation;
      AnimationController _animationController;
    
      GoogleSignIn _googleSignIn;
      GoogleSignInAccount _googleSignInAccount;
      GoogleSignInAuthentication _googleSignInAuthentication;
      FirebaseAuth _auth;
    
     // FacebookLoginResult _facebookLoginResult;
      // FacebookLogin _facebookLogin;
       // FirebaseUser facebookUser;
    
      @override
      void initState() {
        super.initState();
        _animationController =
            AnimationController(vsync: this, duration: Duration(seconds: 4));
        _animation = Tween<double>(begin: -1.0, end: 0.0).animate(CurvedAnimation(
            parent: _animationController, curve: Curves.fastOutSlowIn));
    
        _animationController.forward();
      }
    
      @override
      void dispose() {
        _animationController.dispose();
        super.dispose();
      }
    
     @override
      Widget build(BuildContext context) {
    return widget();
    }
    }
    

    If you use the TickelProvider in this way then you can simply pass this as the value for the vsync.