Flutter: Make widget spin forever

Wanna make a widget spin forever in Flutter? Use this!

Problem

You want to make a widget spin/rotate continuously in flutter, maybe an icon, but there's no simple way to do it.

Here's a little class you can use.

Solution

1) Add this class to your project in a file, e.g. spinning_forever.dart:

import 'package:flutter/material.dart';
import 'dart:math' as math;

/// Make a widget spin forever.
class ForeverSpinning extends StatefulWidget {
  /// The thing you want to rotate
  final Widget child;

  /// Try 1 - 10 (Lower is faster)
  final int speed;

  ForeverSpinning({
    Key? key,
    required this.speed,
    required this.child,
  }) : super(key: key);

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

class _ForeverSpinningState extends State<ForeverSpinning>
    with TickerProviderStateMixin {
  AnimationController? _animationController;

  @override
  void initState() {
    super.initState();
    _animationController = AnimationController(
      duration: Duration(seconds: (widget.speed < 1) ? 1 : widget.speed),
      vsync: this,
    );

    _animationController!.repeat();
  }

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

  @override
  Widget build(BuildContext context) {
    return SpinningWidgetItem(
      controller: _animationController!,
      child: widget.child,
    );
  }
}

class SpinningWidgetItem extends AnimatedWidget {
  final Widget child;
  const SpinningWidgetItem({
    Key? key,
    required AnimationController controller,
    required this.child,
  }) : super(
          key: key,
          listenable: controller,
        );

  @override
  Widget build(BuildContext context) {
    return Transform.rotate(
      angle: (listenable as Animation<double>).value * 2.0 * math.pi,
      child: child,
    );
  }
}

2) Use it, e.g:

ForeverSpinning(
  speed: 5,
  child: Icon(
    Icons.sensors_rounded,
    size: 150,
    semanticLabel: 'Checking for live stream',
  ),
),

3) Done.

This will repeat forever and auto-dispose when you navigate away from the page.

Conclusion

Enjoy the spinning and let me know if you use it, especially if you modified it.

Hope this helps!

Source inspiration

Comments: