Thuan Nguyen
Thuan Nguyen

Love sweet potatoes

Flutter animations basic way

Flutter animations basic way

There are a sereval ways to implement animations in Flutter, today I will show you the basic way to do it. This way will need 2 object, an controller to handle duration of animation, and animation widget handle the begin and end value of animation.

  1. First create an animation controller
    1
    
    AnimationController? _controller;
    
  2. And create an animation widget
    1
    
    Animation<Size>? _heightAnimation;
    
  3. Add Ticker Provider mixin to your stateful widget
    1
    
    with SingleTickerProviderStateMixin
    
  4. Initialize animation
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    
    @override
    void initState() {
     supper.initState();
    
     _controller = AnimationController(
         vsync: this,
         duration: const Duration(
             milliseconds: 300,
         ),
     );
    
     _heightAnimation = Tween<Size>(
         begin: const Size(
             double.infinity,
             260,
         ),
         end: const Size(
             double.infinity,
             320,
         ),
     ).animate(CurveAnimation(
         parent: _controller,
         curve: Curves.linear,
     ));
    
     _heightAnimation?.addListener(() {
         setState(() {});
     });
    }
    
  5. Use in your widget
    1
    
    _heightAnimation?.value.height
    
  6. trigger animation
    1
    2
    3
    
    _controller?.forward();
    // or
    _controller?.reverse();
    
  7. remember to dispose animation to prevent memory leak
    1
    2
    3
    4
    5
    
    @override
    void dispose() {
     super.dispose();
     _controller?.dispose();
    }
    

There is a drawback of this way, the animation will always rebuild the widget when the state changes, so there is a better way is use Animation Builder to improve app performance.