Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

preface

We began to Flutter animation related chapters, through dynamic effect in the application of can bring more enjoyable experience to the user, is a typical example of this is some live platform dynamic effect, such as sending rockets can make the dynamic effect of rocket – feel there times face, of course, this is the enjoyment of the local tyrants, I wait for the code farmers only seen in the video 😂 😂 😂. In this article, we will introduce the basic Animation construction based on Animation class.

Introduction of Animation

Animation is an abstract class that does not participate in screen drawing, but interpolates a range of values within a set event range. Interpolation can be linear, curvilinear, a step function, or anything else imaginable. Objects of this class can know the current value and state (done or gone). The Animation class provides a listening callback method that is called when its value changes:

@override
void addListener(VoidCallback listener);
Copy the code

Therefore, in the listener callback, we can refresh the interface and control the position, size, and Angle of the UI components by using the latest value of the Animation object to achieve the effect of Animation. The Animation class is usually used in conjunction with the AnimationController.

AnimationController profile

AnimationController is a special Animation class that inherits from Animation< Double >. The AnimationController generates a new value every time the hardware is ready to draw the next frame. By default the AnimationController produces a linear sequence of values from 0 to 1.0 over a given time range (usually 60 values per second to achieve 60 FPS). For example, the following code builds a 2-second AnimationController.

var controller =
    AnimationController(duration: const Duration(seconds: 2), vsync: this);
Copy the code

AnimationController has methods to control animation, such as forward, reverse, and so on, and is usually used to control the start and resumption of animation.

The link between Animation and AnimationController is the Animatable class, which is also an abstract class. Common implementation classes include Tween

(linear interpolation) and CurveTween (curve interpolation). The Animatable class has an animate method that takes an Animation< Double > class parameter (usually an AnimationController) and returns an Animation object.

Animation<T> animate(Animation<double> parent) {
  return _AnimatedEvaluation<T>(parent, this);
}
Copy the code

The animate method uses a given Animation

object to drive an Animation, but the range of values used is its own, allowing you to build a custom range of values for an Animation. For example, to build a dynamic effect that increases from 0 to 100 in 2 seconds, use the following code.

var controller =
        AnimationController(duration: const Duration(seconds: 2), vsync: this);
var animation = Tween<double>(begin: 0, end: 100).animate(controller);
Copy the code

Application – Three strands of love

With the above foundation, we can start the small test, we first to a love three zoom in and out of the dynamic effect, as shown below, the first click gradually zoom in, click again gradually zoom back to the original.

Interface code is very simple, three love is actually usedStackPut three hearts in different colorsIconComponents are superimposed and then passedAnimtionThe value of the object changesIconThe size of the. inAnimationValue changes to the listening callback used by leesetStateJust refresh the screen. The complete code is as follows:

import 'package:flutter/material.dart';

class AnimtionDemo extends StatefulWidget {
  const AnimtionDemo({Key? key}) : super(key: key);

  @override
  _AnimtionDemoState createState() => _AnimtionDemoState();
}

class _AnimtionDemoState extends State<AnimtionDemo>
    with SingleTickerProviderStateMixin {
  late Animation<double> animation;
  late AnimationController controller;

  @override
  void initState() {
    super.initState();
    controller =
        AnimationController(duration: const Duration(seconds: 1), vsync: this);
    animation = Tween<double>(begin: 40, end: 100).animate(controller) .. addListener(() { setState(() {}); }); controller.addStatusListener((status) {print(status);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Animation Animation'),
      ),
      body: Center(
        child: Stack(
          alignment: Alignment.center,
          children: [
            Icon(
              Icons.favorite,
              color: Colors.red[100],
              size: animation.value * 1.5,
            ),
            Icon(
              Icons.favorite,
              color: Colors.red[400],
              size: animation.value,
            ),
            Icon(
              Icons.favorite,
              color: Colors.red[600],
              size: animation.value / 2,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.play_arrow, color: Colors.white),
        onPressed: () {
          if (controller.status == AnimationStatus.completed) {
            controller.reverse();
          } else{ controller.forward(); }},),); }@override
  void dispose() {
    controller.dispose();
    super.dispose(); }}Copy the code

Here in _AnimtionDemoState is mixed with SingleTickerProviderStateMixin, here is actually offers AnimationController a TickerProivder object. The TickerProivder object triggers an onTick callback before each frame refresh to update the value of the AnimationController.

conclusion

This article introduces the use of the Flutter Animation builder classes Animation and AnimationController. These two classes allow you to implement many basic Animation effects, such as the common progress bar, scaling, rotation, movement, etc. Next we’ll look at other ways to implement animations and other types of Animation effects based on Animation.

Say, all see here, is not also to this code farmer to love three even?

I am dao Code Farmer with the same name as my wechat official account. This is a column about the introduction and practice of Flutter, providing systematic learning articles about Flutter. See the corresponding source code here: The source code of Flutter Introduction and Practical column. If you have any questions, please add me to the wechat account: island-coder. If you feel you have something to gain, please give three pairs of love as follows:

👍🏻 : a praise to encourage!

🌟 : Collect articles, easy to look back!

💬 : Comment exchange, mutual progress!