Animations

Animations are great part of any Flutter App

in Flutter Animations are broadly divided into two parts

  1. Implicit Animations
  2. Explicit Animations


Implicit Animations

With Flutter’s animation library, you can add motion and create visual effects for the widgets in your UI. One part of the library is an assortment of widgets that manage animations for you. These widgets are collectively referred to as implicit animations, or implicitly animated widgets, deriving their name from the ImplicitlyAnimatedWidget class that they implement.


Explicit Animations

Explicit animations are a set of controls for telling Flutter how to rapidly rebuild the widget tree while changing widget properties to create animation effects. This approach enables you to create effects that you can’t achieve using implicit animations

Suppose you want to create your own Flutter animation without using the animations library. Start with the simplest case possible: Your goal is to animate a ball so that it repeatedly bounces up and down. The following example demonstrates a first attempt using a naive approach. Can you spot the lines of code that create the effect?

import 'dart:async';
import 'package:flutter/material.dart';

Future<void> main() async {
  runApp(
    MyApp(),
  );
}
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: Center(
          child: BouncingBallDemo(),
        ),
      ),
    );
  }
}

class BouncingBallDemo extends StatefulWidget {
  @override
  _BouncingBallDemoState createState() => _BouncingBallDemoState();
}


class _BouncingBallDemoState extends State<BouncingBallDemo> {
  late double marginTop;


  void changePosition(Timer t) async {
    setState(() {
      marginTop = marginTop == 0 ? 100 : 0;
    });
  }


  @override
  void initState() {
    super.initState();
    marginTop = 0;
    Timer.periodic(const Duration(seconds: 1), changePosition);
  }


  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.only(top: marginTop),
      child: Container(
        decoration: BoxDecoration(
          shape: BoxShape.circle,
          color: Colors.green,
        ),
        width: 40.0,
        height: 40.0,
      ),
    );
  }
}

The preceding example uses the container’s margin property to alternate the position of the ball on the screen, and a periodic timer to control how frequently the ball changes its position (once every second). As a viewer, this approach leaves a lot to be desired. The ball only has two positions, so the animation looks pretty choppy—you could easily mistake the animation for a glitch. To describe this problem in animation terms, you would say that the animation alternates between only two frames:


flutter-animations