Flutter – Animation with AnimatedContainer

Flutter is awesome because it provides a rich “ready to use” widgets and the ease of how we can make animation. Especially for animation, Flutter also provides many built-in “animated” widgets. In this post, we will learn about one of the most common animated widgets, it is AnimatedContainer.

Here is the the demo we will build:

Some notes before we start

  • There is no magic here, AnimatedContainer is just a Container with implicit animation. Flutter handles the “animated” part for us, we just need to construct our Container as usual, plus adding the Duration (of animation – required) and animation Curve (optional).

AnimatedContainer = Container + Implicit Animation

  • All we need to do is simply change the state(s) (color, width, height, padding…) of the Container, then call setState() to trigger the animation.
  • In this post, I only show you the animation of color and width/height. But you can do many kinds of animation with AnimatedContainer: border, border radius, shadow, padding, alignment…

💻 Let’s code


1. Create a “fixed” (non-animated) Container

import 'package:flutter/material.dart';

void main() => runApp(AnimatedContainerDemo());

class AnimatedContainerDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Coflutter - AnimatedContainer ',
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Coflutter - AnimatedContainer'),
          backgroundColor: const Color(0xffae00f0),
        ),
        body: AnimatedContainerDemoScreen(),
      ),
    );
  }
}

class AnimatedContainerDemoScreen extends StatefulWidget {
  @override
  _AnimatedContainerDemoScreenState createState() =>
      _AnimatedContainerDemoScreenState();
}

class _AnimatedContainerDemoScreenState
    extends State<AnimatedContainerDemoScreen> {
  int duration = 300;
  double width = 100;
  double height = 100;
  Color color = Colors.blue;

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          AnimatedContainer(
            duration: Duration(milliseconds: duration),
            width: width,
            height: height,
            color: color,
            curve: Curves.fastOutSlowIn,
          ),
        ],
      ),
    );
  }
}


2. Create methods to change the states of the Container

import 'dart:math';

// ...

class _AnimatedContainerDemoScreenState
    extends State<AnimatedContainerDemoScreen> {
// ...
void _animateContainerSize() {
    Random random = Random();
    setState(() {
      width = (random.nextInt(150) + 50).toDouble();
      height = (random.nextInt(150) + 50).toDouble();
      duration = 300;
    });
  }

  void _animateContainerColor() {
    setState(() {
      // Generate random color
      color = Colors.primaries[Random().nextInt(Colors.primaries.length)];
      duration = 500;
    });
  }
}


3. Create a few buttons, connect them to above methods

import 'dart:math';

import 'package:flutter/material.dart';

void main() => runApp(AnimatedContainerDemo());

class AnimatedContainerDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Coflutter - AnimatedContainer ',
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Coflutter - AnimatedContainer'),
          backgroundColor: const Color(0xffae00f0),
        ),
        body: AnimatedContainerDemoScreen(),
      ),
    );
  }
}

class AnimatedContainerDemoScreen extends StatefulWidget {
  @override
  _AnimatedContainerDemoScreenState createState() =>
      _AnimatedContainerDemoScreenState();
}

class _AnimatedContainerDemoScreenState
    extends State<AnimatedContainerDemoScreen> {
  int duration = 300;
  double width = 100;
  double height = 100;
  Color color = Colors.blue;

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          AnimatedContainer(
            duration: Duration(milliseconds: duration),
            width: width,
            height: height,
            color: color,
            curve: Curves.fastOutSlowIn,
          ),
          SizedBox(height: 10,),
          Wrap(
            spacing: 10,
            runSpacing: 10,
            children: [
              RaisedButton(
                child: Text('Animate Size'),
                onPressed: _animateContainerSize,
              ),
              RaisedButton(
                child: Text('Animate Color'),
                onPressed: _animateContainerColor,
              ),
              RaisedButton(
                child: Text('Animate Size & Color'),
                onPressed: () {
                  _animateContainerColor();
                  _animateContainerSize();
                },
              )
            ],
          )
        ],
      ),
    );
  }

  void _animateContainerSize() {
    Random random = Random();
    setState(() {
      width = (random.nextInt(150) + 50).toDouble();
      height = (random.nextInt(150) + 50).toDouble();
      duration = 300;
    });
  }

  void _animateContainerColor() {
    setState(() {
      // Generate random color
      color = Colors.primaries[Random().nextInt(Colors.primaries.length)];
      duration = 500;
    });
  }
}


That’s it.
If you are looking for a developer or a team to build you next projects, please Drop us your request!

Tagged : / / / /
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x