Open In App

AnimatedSize Flutter

Last Updated : 23 Jul, 2025
Comments
Improve
Suggest changes
1 Likes
Like
Report

In mobile app development, animations and transitions play a major role in providing a simple and smooth user experience, making it visually appealing to the users, and interacting with the app.

What is AnimatedSize in Flutter?

In Flutter, the AnimatedSize widget is a powerful tool that automatically animates the resizing of its child widget when its size changes. It provides a smooth and visually appealing transition, making it an ideal choice for scenarios that require contracting or expanding a widget based on user interactions or state changes in your app.

Using this widget, one can do many things like animate dynamic content, responsive UI animations, gamification, interactive elements animation, etc. Here's the official documentation of the AnimatedSize class in Flutter.

Constructor of AnimatedSize

AnimatedSize AnimatedSize({
Key? key,
Widget? child,
AlignmentGeometry alignment = Alignment.center,
Curve curve = Curves.linear,
required Duration duration,
Duration? reverseDuration,
Clip clipBehavior = Clip.hardEdge,
void Function()? onEnd,
})

Here are several constraints and properties that come with the AnimatedSize widget in Flutter that you can use to customize and fine-tune the animation behavior.

Constraint

Description

duration

This constraint specifies the duration of the size animation.

It accepts a Duration object and can set the duration of the animation in milliseconds. Longer Duration will result in slower animation, while Shorter Duration makes the animation faster.

curve

This constraint defines the rate of change during the animation (e.g., ease in, ease out, linear).

Flutter provides various pre-defined curve options like Curves. linear, which Curves.easeIn, Curves.easeOut, Curves.easeInOut, etc. You can also create custom curves using the Cubic or Curve classes.

alignment

The alignment constraint determines the alignment of the child widget within the AnimatedSize widget during the animation. It accepts an AlignmentGeometry value, which can be used to specify the alignment along the x and y axes.

This is particularly useful when you want to control the position of the child widget as it grows or shrinks during the animation.

reverseDuration

This constraint allows you to specify a separate duration for the reverse animation, which occurs when the child widget shrinks in size.

By default, the reverseDuration is set to the same value as the duration, but you can override it to have a different animation duration for the contraction phase.

clipBehavior

The clipBehavior constraint determines how the child widget should be clipped during the animation. It accepts a Clip value, which can be a Clip.none (default), Clip.hardEdge, or Clip.antiAlias.

This constraint is useful when you want to control the clipping behavior of the child widget, especially when it extends beyond its parent's boundaries during the animation.

child

This is a required constraint that specifies the child widget to be animated by the AnimatedSize widget.

You can pass any widget or widget tree as the child of AnimatedSize.

Step-by-Step Implementation

We will learn how to implement AnimatedSize in Flutter as mentioned below:

Step 1: Create a new Flutter Application

Create a new Flutter application using the command Prompt. To create a new app, write the following command and run it.

flutter create app_name

To know more about it refer this article: Creating a Simple Application in Flutter

Step 2: Import required packages :

import 'package:flutter/material.dart';

Step 3: Main function

void main() {
runApp(MyApp());
}

The main function is the entry point of the Flutter app, calling runApp(MyApp()) to start the app.

Step 4: Defining MyApp

Dart
// Root widget of the application
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      // Title used by the OS (not shown in UI)
      title: 'GeeksforGeeks Text Example',

      // Theme configuration for the app
      theme: ThemeData(
        primaryColor: Color(0xFF5CB85C), // Custom green color for branding
      ),

      debugShowCheckedModeBanner: false, // Removes the debug banner from UI

      home: MyHomePage(), // Sets the home page of the app
    );
  }
}


MyApp is a stateless widget that returns a MaterialApp with a title, theme, and home set to MyHomePage.


Step 5: Define MyHomePage Stateful Widget

Dart
// A StatefulWidget to manage dynamic UI changes
class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState(); // Creates state object
}

// State class for MyHomePage
class _MyHomePageState extends State<MyHomePage> {
      // Boolean variable to toggle expansion state
      bool _isExpanded = false;


Step 6: Build Method of _MyHomePageState

Dart
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // Top app bar of the screen
      appBar: AppBar(
        title: Text('GeeksforGeeks AnimatedSize'), // Title in the app bar
        backgroundColor: Colors.green, // Background color of app bar
        foregroundColor: Colors.white, // Text/icon color of app bar
      ),

      // Body of the Scaffold
      body: Center(
        child: Column(
          mainAxisAlignment:
              MainAxisAlignment.center, // Center children vertically
          children: [
            // AnimatedSize widget to animate size transitions
            AnimatedSize(
              duration: Duration(milliseconds: 1000), // Animation duration
              curve: Curves.elasticOut, // Animation curve for effect
              alignment:
                  _isExpanded
                      ? Alignment.center
                      : Alignment.topCenter, // Alignment based on toggle
              reverseDuration: Duration(
                milliseconds: 500,
              ), // Duration when shrinking
              clipBehavior:
                  Clip.antiAlias, // Smooth clipping for rounded corners
              // Child widget whose size changes
              child: Container(
                width: _isExpanded ? 300.0 : 100.0, // Width based on state
                height: _isExpanded ? 100.0 : 50.0, // Height based on state
                decoration: BoxDecoration(
                  color: Theme.of(context).primaryColor, // Background color
                  borderRadius: BorderRadius.circular(
                    _isExpanded ? 20.0 : 10.0,
                  ), // Rounded corners
                ),
                child: Center(
                  child: Text(
                    'GeeksforGeeks', // Text displayed inside the container
                    style: TextStyle(
                      color: Colors.white, // Text color
                      fontSize:
                          _isExpanded ? 24.0 : 12.0, // Font size based on state
                      fontWeight: FontWeight.bold, // Bold text
                    ),
                  ),
                ),
              ),
            ),

            SizedBox(height: 16.0), // Spacing between animated box and button
            // Button to toggle the size of the container
            ElevatedButton(
              onPressed: () {
                setState(() {
                  _isExpanded = !_isExpanded; // Toggle the state value
                });
              },
              style: ElevatedButton.styleFrom(
                backgroundColor: Theme.of(context).primaryColor, // Button color
              ),
              child: Text(
                _isExpanded
                    ? 'Collapse'
                    : 'Expand', // Button label based on state
                style: TextStyle(
                  color: Colors.white, // Button text color
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }


  • The build method returns a Scaffold with an AppBar and a Center widget.
  • The Center contains a Column with an AnimatedSize widget that animates a Container based on _isExpanded.
  • An ElevatedButton toggles _isExpanded when pressed, causing the animation to play

Complete Source Code

main.dart:

main.dart
// Importing the Flutter material design library
import 'package:flutter/material.dart';

// Entry point of the Flutter application
void main() {
  runApp(MyApp()); // Launches the app and starts with MyApp widget
}

// Root widget of the application
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      // Title used by the OS (not shown in UI)
      title: 'GeeksforGeeks Text Example',

      // Theme configuration for the app
      theme: ThemeData(
        primaryColor: Color(0xFF5CB85C), // Custom green color for branding
      ),

      debugShowCheckedModeBanner: false, // Removes the debug banner from UI

      home: MyHomePage(), // Sets the home page of the app
    );
  }
}

// A StatefulWidget to manage dynamic UI changes
class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState(); // Creates state object
}

// State class for MyHomePage
class _MyHomePageState extends State<MyHomePage> {
  // Boolean variable to toggle expansion state
  bool _isExpanded = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // Top app bar of the screen
      appBar: AppBar(
        title: Text('GeeksforGeeks AnimatedSize'), // Title in the app bar
        backgroundColor: Colors.green, // Background color of app bar
        foregroundColor: Colors.white, // Text/icon color of app bar
      ),

      // Body of the Scaffold
      body: Center(
        child: Column(
          mainAxisAlignment:
              MainAxisAlignment.center, // Center children vertically
          children: [
            // AnimatedSize widget to animate size transitions
            AnimatedSize(
              duration: Duration(milliseconds: 1000), // Animation duration
              curve: Curves.elasticOut, // Animation curve for effect
              alignment:
                  _isExpanded
                      ? Alignment.center
                      : Alignment.topCenter, // Alignment based on toggle
              reverseDuration: Duration(
                milliseconds: 500,
              ), // Duration when shrinking
              clipBehavior:
                  Clip.antiAlias, // Smooth clipping for rounded corners
              // Child widget whose size changes
              child: Container(
                width: _isExpanded ? 300.0 : 100.0, // Width based on state
                height: _isExpanded ? 100.0 : 50.0, // Height based on state
                decoration: BoxDecoration(
                  color: Theme.of(context).primaryColor, // Background color
                  borderRadius: BorderRadius.circular(
                    _isExpanded ? 20.0 : 10.0,
                  ), // Rounded corners
                ),
                child: Center(
                  child: Text(
                    'GeeksforGeeks', // Text displayed inside the container
                    style: TextStyle(
                      color: Colors.white, // Text color
                      fontSize:
                          _isExpanded ? 24.0 : 12.0, // Font size based on state
                      fontWeight: FontWeight.bold, // Bold text
                    ),
                  ),
                ),
              ),
            ),

            SizedBox(height: 16.0), // Spacing between animated box and button
            // Button to toggle the size of the container
            ElevatedButton(
              onPressed: () {
                setState(() {
                  _isExpanded = !_isExpanded; // Toggle the state value
                });
              },
              style: ElevatedButton.styleFrom(
                backgroundColor: Theme.of(context).primaryColor, // Button color
              ),
              child: Text(
                _isExpanded
                    ? 'Collapse'
                    : 'Expand', // Button label based on state
                style: TextStyle(
                  color: Colors.white, // Button text color
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

This code will create a Text Animation, expanding and collapsing the size when the button is clicked.

Output :



Explore