Back to all posts

Animated Widgets in Flutter

In Flutter, animated widgets make it easy to add smooth animations to your app. They help you create dynamic effects with simple code. In this article, we'll look at some of the most commonly used animated widgets. Whether you want to animate positions, sizes, or other changes, these widgets will help you do it easily.

List Of Widgets mentioned in this Article

  • Animated Positioned
  • Animated Scale
  • Animated Align
  • Animated Container
  • Animated Opacity
  • Animated Size
  • Animated Switcher
  • Animated List

Animated Positioned

The AnimatedPositioned widget in Flutter is like a regular Positioned widget, but with a cool twist—it smoothly animates changes in position over time. This widget only works when it is a child of a Stack.

Positioned Widget: Normally, you use the Positioned widget inside a Stack to place a widget at a specific location (using top, bottom, left, or right). This AnimatedPositioned Widget does the same thing but adds animation when the position changes. For example, if you change the top value, the widget will slide to the new position instead of jumping instantly.

AnimatedPositioned(
  duration: const Duration(milliseconds: 300),
  top: hideAppbar ? -kToolbarHeight : 0,
  left: 0,
  right: 0,
  child: Container(
    height: kToolbarHeight,
    color: Colors.white,
    child: const Text(
      'Animated Positioned AppBar',
      textAlign: TextAlign.center,
      style: TextStyle(
        color: Colors.black,
        fontSize: 20,
        fontWeight: FontWeight.bold,
      ),
    ),
  ),
);

Animated Scale

The AnimatedScale widget in Flutter is like a magnifying glass for your widgets—it smoothly animates changes in the scale of a widget, making it bigger or smaller.

Scale Widget: Normally, to scale a widget, you'd use a Transform.scale widget. However, that change would be instant. The AnimatedScale widget does the same thing but with a smooth animation when the scale factor changes. The scale parameter defines the size of the widget relative to its original size, where 1.0 is the original size and values greater than 1.0 scale up the widget.

Column(
  crossAxisAlignment: CrossAxisAlignment.center,
  mainAxisAlignment: MainAxisAlignment.center,
  children: [
    AnimatedScale(
      scale: scaleImage ? 2.0 : 1.0,
      duration: const Duration(milliseconds: 500),
      child: Image.network(
        "https://onlyflutter.com/wp-content/uploads/2024/03/flutter_banner_onlyflutter.png",
        width: 200,
        height: 200,
      )
    ),
    const SizedBox(height: 16),
    ElevatedButton(
      onPressed: () {
        setState(() {
          scaleImage = !scaleImage;
        });
      },
      child: const Text('Scale Image'),
    ),
  ],
);

Animated Align

The AnimatedAlign widget in Flutter animates changes in the alignment of a child widget within its parent. This widget smoothly transitions the child's position from one alignment to another over time.

Alignment: Normally, you use the Align widget to position a child within its parent based on an alignment value (e.g., top-left, center). The AnimatedAlign widget adds animation to this transition, making the movement between alignments smooth and visually appealing.

Column(
  crossAxisAlignment: CrossAxisAlignment.center,
  mainAxisAlignment: MainAxisAlignment.center,
  children: [
    AnimatedAlign(
      alignment: isAligned ? Alignment.bottomRight : Alignment.topLeft,
      duration: const Duration(milliseconds: 500),
      child: Container(
        width: 100,
        height: 100,
        color: Colors.black,
        child: const Center(
          child: Text(
            'Animated Align',
            textAlign: TextAlign.center,
            style: TextStyle(
              color: Colors.white,
              fontSize: 16,
            ),
          ),
        ),
      ),
    ),
    ElevatedButton(
      onPressed: () {
        setState(() {
          isAligned = !isAligned;
        });
      },
      child: const Text('Toggle Align'),
    ),
  ],
);

Animated Container

The AnimatedContainer widget in Flutter lets you smoothly animate changes to things like size, color, and padding. It makes your UI more dynamic by transitioning between different states smoothly.

Container: Normally, you use a Container to create a box with properties like width, height, color, and padding. AnimatedContainer does the same but adds smooth animations when these properties change.

AnimatedContainer(
  duration: const Duration(milliseconds: 300),
  width: isExpanded ? 200.0 : 100.0,
  height: isExpanded ? 200.0 : 100.0,
  color: isExpanded ? Colors.black : Colors.red,
  padding: isExpanded
      ? const EdgeInsets.all(20.0)
      : const EdgeInsets.all(10.0),
  child: const Center(
    child: Text(
      'Animated Container',
      style: TextStyle(
        color: Colors.white,
        fontSize: 16,
      ),
    ),
  ),
);

Animated Opacity

The AnimatedOpacity widget in Flutter animates changes to a widget's transparency. It allows you to smoothly fade a widget in or out, making it more dynamic and engaging.

Opacity: Usually, you use the Opacity widget to make a widget more or less transparent. AnimatedOpacity extends this by animating the fade effect over a set duration.

SizedBox(
  height: 100,
  child: ListView.separated(
    shrinkWrap: true,
    scrollDirection: Axis.horizontal,
    itemCount: _images.length,
    itemBuilder: (context, index) {
      return AnimatedOpacity(
        duration: const Duration(milliseconds: 500),
        opacity: _selectedImageIndex == index ? 1 : 0.3,
        child: InkWell(
          onTap: () {
            setState(() {
              _selectedImageIndex = index;
            });
          },
          child: Image.network(
            _images[index],
            height: 100,
            width: 100,
          ),
        ),
      );
    },
    separatorBuilder: (context, index) {
      return const SizedBox(width: 16);
    },
  ),
);

Animated Size

The AnimatedSize widget in Flutter animates changes in a widget's size. It smoothly transitions the widget's dimensions, making your UI more fluid and interactive.

Column(
  crossAxisAlignment: CrossAxisAlignment.center,
  mainAxisAlignment: MainAxisAlignment.center,
  children: [
    ColoredBox(
      color: Colors.black,
      child: AnimatedSize(
        duration: const Duration(seconds: 1),
        curve: Curves.easeIn,
        child: SizedBox.square(
          dimension: _changeBoxSize ? 200.0 : 100.0,
          child: const Center(
            child: Text(
              "Animated Box",
              style: TextStyle(color: Colors.white),
            ),
          ),
        ),
      ),
    ),
    ElevatedButton(
      onPressed: () {
        setState(() {
          _changeBoxSize = !_changeBoxSize;
        });
      },
      child: const Text("Toggle Box Size"),
    ),
  ],
);

Animated Switcher

The AnimatedSwitcher widget in Flutter provides a smooth transition between two widgets when their child changes. It automatically animates the replacement of the old widget with the new one, making your UI transitions smooth.

Column(
  crossAxisAlignment: CrossAxisAlignment.center,
  mainAxisAlignment: MainAxisAlignment.center,
  children: [
    AnimatedSwitcher(
      duration: const Duration(milliseconds: 500),
      child: Image.network(
        _images[_selectedImageIndex],
        key: ValueKey<int>(_selectedImageIndex),
        height: 200,
        width: 200,
        fit: BoxFit.fill,
      ),
    ),
    ElevatedButton(
      onPressed: () {
        setState(() {
          _selectedImageIndex =
              (_selectedImageIndex + 1) % _images.length;
        });
      },
      child: const Text("Switch Image"),
    ),
  ],
);

Animated List

The AnimatedList widget in Flutter allows you to create lists with smooth animations when items are added or removed. It animates changes in the list, making your UI more dynamic and visually appealing.

Scaffold(
  body: AnimatedList(
    key: _listKey,
    initialItemCount: _items.length,
    itemBuilder: (context, index, animation) {
      return SizeTransition(
        sizeFactor: animation,
        child: ListTile(
          title: Text(_items[index]),
          trailing: IconButton(
            icon: const Icon(Icons.delete),
            onPressed: () => _removeItem(index),
          ),
        ),
      );
    },
  ),
  floatingActionButton: FloatingActionButton(
    onPressed: _addItem,
    child: const Icon(Icons.add),
  )
);

Conclusion

There are many more animated widgets available in Flutter to help you create even more impressive animations. That's all for today. Thanks for reading! For any questions or issues, feel free to reach out to me on LinkedIn.