Search code examples
flutterdartflutter-animation

Is there a way to animate the icon of the ElevatedButton.icon() in flutter?


I would like to animate the icon of this ElevatedButton when pressed. The idea was to make the icon spin for a few seconds after pressing this button.

Can anyone help me?

This is the code:

ElevatedButton.icon(
     onPressed: () {},
     icon: const Icon(Icons.sync),
     label: const Padding(
     padding: EdgeInsets.symmetric(horizontal: 8.0),
         child: Text("Sincronizza"),
     )
),

Solution

  • You can use the AnimatedRotation widget to do this easily!

    Code Sample

    class SyncButton extends StatefulWidget {
      const SyncButton({
        super.key,
        required this.onPressed,
      });
    
      final VoidCallback? onPressed;
    
      @override
      State<SyncButton> createState() => _SyncButtonState();
    }
    
    class _SyncButtonState extends State<SyncButton> {
      double turns = 0.0;
    
      @override
      Widget build(BuildContext context) {
        return ElevatedButton.icon(
          onPressed: widget.onPressed != null
              ? () {
                  // Perform half rotation but you can increase the value
                  setState(() => turns += 0.5);
                  widget.onPressed?.call();
                }
              : null,
          icon: AnimatedRotation(
            duration: const Duration(milliseconds: 300),
            turns: turns,
            child: const Icon(Icons.sync),
          ),
          label: const Padding(
            padding: EdgeInsets.symmetric(horizontal: 8.0),
            child: Text("Sincronizza"),
          ),
        );
      }
    }
    

    Try the full example on DartPad

    Result

    enter image description here