Flutter Animated Series (Animated Container)

Murtaza Sulaihi
Flutter Community

--

Hello, friends welcome back to my second story in the Animated Series of Flutter Widget. My first story on Animated Align received a lot of appreciation in terms of reading. Around 2K views and 1K reads within a week and a small celebration for being on the first page of Google’s search. Yay!😁

What is Animated Container?

Well, I am sure you know what a Container widget is, it has basic properties like height, width, background colour, padding, borders, shape and much more, you can read in detail about it in my previous article specifically on the Container widget.

Now, Animated Container involves changing of the above properties mentioned of the Container widget over a duration. You can animate colour, size, border, shape, changing its properties from old to new and animating the change of properties. Animated Container has implicit animations. I know I haven't mentioned about implicit and explicit animations in my last story so I am writing about it below just to understand what it really means and not going into many details.

So there are two types of animation in Flutter.

  1. Explicit animations:- expects an animation controller to animate the widget. Used for more advanced animation which cannot be achieved with implicit animations.
  2. Implicit animations:- built-in animation controller to animate the widget.

First, we will look at the constructor and then I will be posting a couple of examples to understand how Animated Container works and where and how it can be used.

AnimatedContainer({
this.alignment,
this.padding,
Color? color,
Decoration? decoration,
this.foregroundDecoration,
double? width,
double? height,
BoxConstraints? constraints,
this.margin,
this.transform,
this.transformAlignment,
this.child,
this.clipBehavior = Clip.none,
Curve curve = Curves.linear,
required Duration duration,
VoidCallback? onEnd,
})

Almost all the properties are the same as the Container widget. You can check my story on The Container widget where you will learn in detail about it. Now there are two extra properties out which one is required that is the duration and curve property both of which cannot be null. Well, the duration and curve property is what makes the whole animation work.

Now, let us look at a couple of examples to get more understand on how to use the animated container.

Example 1:

In the first example, we are going to change the size of the button from a normal state button to a busy state depicting as if some form has been submitted and we are waiting for a confirmation on it. So the size of the button will change and turn into a circular progress bar.

Step 1:

We are going to create a custom button named as AnimatedBusyButton.

/// A button that shows a busy indicator in place of title when pressed
class AnimatedBusyButton extends StatefulWidget {
final bool busy;
final String title;
final Function onPressed;
final bool enabled;
const AnimatedBusyButton(
{@required this.title,
this.busy = false,
@required this.onPressed,
this.enabled = true});

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

class _AnimatedBusyButtonState extends State<AnimatedBusyButton> {
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: widget.onPressed,
child: InkWell(
child: AnimatedContainer(
height: widget.busy ? 60 : 75,
width: widget.busy ? 60 : 200,
curve: Curves.easeIn,
duration: const Duration(seconds: 1),
alignment: Alignment.center,
padding: EdgeInsets.symmetric(
horizontal: widget.busy ? 10 : 15,
vertical: widget.busy ? 10 : 10),
decoration: BoxDecoration(
color: widget.enabled ? Colors.blue[800] : Colors.blue[300],
borderRadius: BorderRadius.circular(5),
),
child: !widget.busy
? Text(
widget.title,
style: TextStyle(fontSize: 20, color: Colors.white),
)
: CircularProgressIndicator(
strokeWidth: 3,
valueColor:
AlwaysStoppedAnimation<Color>(Colors.yellowAccent)),
),
),
);
}
}

Step 2:

We are going change the state of the busy property from false to true when the button is pressed and it will animate the button and make it smaller and progress indicator will appear instead of the text. You will have to use a stateful widget.

bool busy = false;

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Animated Container Widget'),
),
body: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
AnimatedBusyButton(
title: 'SAVE',
onPressed: () {
setState(() {
busy = !busy;
});
},
busy: busy,
),
]
),
),
);

As soon as you press on the button it will animate itself to a smaller button based on the duration and curve that has been set. You can try out different types of curve property. There are around 41 different types of curves to choose from.

Example 2:

Well, I really love this example, it really gives you great insight into how easy it is to use and you can come up with some great ideas while building your Flutter application. This example is from Flutter Cookbook but I have made a few changes, they have a great library on different widgets teaching on how to use it while building your application.

Step 1:

Create a stateful widget and give it name as per your requirement. And initialize these values.

double _width = 100;
double _height = 100;
Color _color = Colors.green;
BorderRadiusGeometry _borderRadius = BorderRadius.circular(10);

Step 2:

Create Animated Container and assign those values respectively to its properties.

AnimatedContainer(
// Use the properties stored in the State class.
width: _width,
height: _height,
decoration: BoxDecoration(
color: _color,
borderRadius: _borderRadius
,
),
// Define how long the animation should take.
duration: Duration(seconds: 1),
// Provide an optional curve to make the animation feel smoother.
curve: Curves.fastOutSlowIn,
),

Step 3:

You can either create another button to animate the Container or else do as I have done. I have used GestureDetector so that when you tap on the Container it will start animating by changing its shape, colour and border-radius. It is actually really amazing to see as it happens, especially for first-time coders.

GestureDetector(
onTap: () {
setState(() {
// Create a random number generator.
final random = Random();

// Generate a random width and height.
_width = random.nextInt(300).toDouble();
_height = random.nextInt(300).toDouble();

// Generate a random color.
_color = Color.fromRGBO(
random.nextInt(256),
random.nextInt(256),
random.nextInt(256),
1,
);

// Generate a random border radius.
_borderRadius =
BorderRadius.circular(random.nextInt(100).toDouble());
});
},
child: InkWell(
child: AnimatedContainer(
// Use the properties stored in the State class.
width: _width,
height: _height,
decoration: BoxDecoration(
color: _color,
borderRadius: _borderRadius,
),
// Define how long the animation should take.
duration: Duration(seconds: 1),
// Provide an optional curve to make the animation feel smoother.
curve: Curves.fastOutSlowIn,
),
),
),

See the magic happen when you tap on the container, every time you tap it will change its shape, colour and border-radius randomly.

You can see all the three above examples into action below.

I have come to the end of my story and I really would appreciate it if you would share this story with whomever you may think will benefit from it. And a few 50 👏claps will bring a great smile😊 on my face. I know there are a lot of enthusiastic developers and more popular writers are writing about different animated widgets, with that said I hope I make a difference. My main aim behind writing about Flutter widgets is learning, it gives me an opportunity to explore, experiment and learn deeply about it which eventually makes me a better developer. If you agree with me lets have a Cup of Coffee ☕️. I am leaving links to my previous stories, do read it and share.

Links to my previous stories SafeArea Widget, Expanded & Flexible, Container Widget, Row and Column, Stack & Positioned, Boxes Part-1, Boxes Part-2, TabBar & TabBarView, GridView, Buttons, Scaffold Widget.

Link to my animated series Animated Align.

Care to follow me… Instagram, Twitter, Linkedin, Reddit.

https://www.twitter.com/FlutterComm

--

--

Murtaza Sulaihi
Flutter Community

By profession, I am a school professor and I also develop Android applications and also Flutter applications.