How to use AnimatedIcon widget in Flutter

The AnimatedIcon widget in Flutter allows us to create and animate icons using predefined icon animations easily. It's a convenient way to add engaging and dynamic visual effects to our Flutter app. In this answer, we'll walk through the steps of using the AnimatedIcon widget, from importing the necessary packages to implementing the animation.

Constructor and parameters

The AnimatedIcon widget provides a constructor with various parameters to customize its behavior and layout.

const AnimatedIcon({
  Key? key,
  required AnimatedIconData icon,
  required Animation<double> progress,
  Color? color,
  double? size,
  String? semanticLabel,
  TextDirection? textDirection
})

Let's take a closer look at each parameter and its purpose:

  • key: An optional key that uniquely identifies the widget.

  • icon: The specific animated icon to display and animate.

  • progress: The animation progress is controlled by an animation controller.

  • color: The color to apply to the icon.

  • size: The size of the icon.

  • semanticLabel: An optional label for accessibility.

  • textDirection: The text direction for the semantic label, if provided.

The progress and icon variable can't be null.

Importing necessary libraries

Before using the AnimatedIcon widget, make sure to import the required libraries in our Dart file:

import 'package:flutter/material.dart';

Choose an animated icon

Flutter provides a set of predefined animated icons that we can choose from. We can find the complete list of available icons in the official Flutter documentation. For this Answer, let's use the AnimatedIcons.play_pause icon.

Create an AnimatedIcon widget

To create an AnimatedIcon widget, use the following code:

AnimatedIcon(
icon: AnimatedIcons.play_pause,
progress: _animationController, // Replace with your animation controller
)

We need to replace _animationController with our own animation controller. The progress property should be linked to an animation controller, allowing us to control the animation's progress.

Set up the animation controller

Before using the AnimatedIcon, we need to set up an animation controller. Here's an example of how we can create an animation controller:

AnimationController _animationController;
@override
void initState() {
super.initState();
_animationController = AnimationController(
vsync: this,
duration: Duration(milliseconds: 300),
); // Adjust duration as needed
}

Make sure your class extends StatefulWidget and implements the TickerProviderStateMixin.

Toggle the animation

We can toggle the animation by changing the animation controller's value. For example, we can use a GestureDetector to toggle the animation when a user taps on a widget:

GestureDetector(
onTap: () {
if (_animationController.isDismissed) {
_animationController.forward();
} else {
_animationController.reverse();
}
},
child: AnimatedIcon(
icon: AnimatedIcons.play_pause,
progress: _animationController,
),
)

This code snippet will play the animation when the user taps the widget and pause it when tapped again.

Dispose of resources

Don't forget to dispose of the animation controller to prevent memory leaks:

@override
void dispose() {
_animationController.dispose();
super.dispose();
}

Output

After running the above code, we can see the following output:

Code example

We get the following output by putting together the code explained above.

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'AnimatedIcon Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage>
    with TickerProviderStateMixin {
  late AnimationController _animationController;

  @override
  void initState() {
    super.initState();
    _animationController = AnimationController(
      vsync: this,
      duration: Duration(milliseconds: 300),
    );
  }

  @override
  void dispose() {
    _animationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Educative AnimatedIcon Answer'),
      ),
      body: Center(
        child: GestureDetector(
          onTap: () {
            if (_animationController.isDismissed) {
              _animationController.forward();
            } else {
              _animationController.reverse();
            }
          },
          child: AnimatedIcon(
            icon: AnimatedIcons.play_pause,
            progress: _animationController,
            size: 50.0,
            color: Colors.blue,
            semanticLabel: 'Play/Pause',
          ),
        ),
      ),
    );
  }
}

Conclusion

The AnimatedIcon widget in Flutter provides a powerful and efficient way to incorporate animated icons into our app's user interface. Leveraging the provided animation controller, customizable parameters such as color and size, and seamless toggling functionality, we can create dynamic and interactive icon animations that contribute to a polished and captivating user experience.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved