Search code examples
flutteranimationcontroller

Irregular behavior of animation


I tried to incorporate animation in my project where there would be a stack of Blue container and Yellow container and when the screen is tapped the upper container would slide down and when tapped again would slide up( the upper one is yellow), very much like Backdrop Scaffold

Code

 AnimationController _animationController;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _animationController=AnimationController(
      duration: Duration(milliseconds: 250),
      vsync: this
    )..repeat();
  }

  void toggle()=>_animationController.isDismissed? _animationController.forward()
      :_animationController.reverse();


  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: (){
        toggle();
      },
      child: AnimatedBuilder(
       animation: _animationController,
       builder: (_,__){
         double slide=1.0-_animationController.value*0.3;
         double align=(MediaQuery. of(context). size. height-150.0
         )*_animationController.value;


         return Stack(
           children: <Widget>[
             Container(
               color: Colors.blue,
             ),
             Transform(
               transform: Matrix4.identity()
                 //..scale(slide)
                 ..translate(0.0,align),
               alignment: Alignment.bottomCenter ,
              
               child: Container(
                 width: double.infinity,
                 height: double.infinity,

                 decoration: BoxDecoration(
                     color: Colors.yellow,
                   borderRadius: BorderRadius.circular(12.0)
                 ),
               ),
             )
           ],
         );
       },
      ),
    );

@override
  void dispose() {
    // TODO: implement dispose
    _animationController.dispose();
    super.dispose();
  }

Now whenever I restart the app or open the app the yellow container just up and down and up continuously without any tapping, it stops only after tap


Solution

  • According to the documentation: The .repeat method Starts running the animation in the forward direction, and restarts the animation when it completes.

    To fix the issue, remove the ..repeat method attached to the animationControlller object. I added a demo code of how it should be:

     @override
      void initState() {
        // TODO: implement initState
        super.initState();
        _animationController =
            AnimationController(duration: Duration(milliseconds: 250), vsync: this);
      }