How to rotate an image using Flutter AnimationController and Transform?

Issue

I have star png image and I need to rotate the star using Flutter AnimationController and Transformer. I couldn’t find any documents or example for image rotation animation.

Any idea How to rotate an image using Flutter AnimationController and Transform?

UPDATE:

class _MyHomePageState extends State<MyHomePage>  with TickerProviderStateMixin {

  AnimationController animationController;

  @override
  void initState() {
    super.initState();
    animationController = new AnimationController(
      vsync: this,
      duration: new Duration(milliseconds: 5000),
    );
    animationController.forward();
    animationController.addListener(() {
      setState(() {
        if (animationController.status == AnimationStatus.completed) {
          animationController.repeat();
        }
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return new Container(
      alignment: Alignment.center,
      color: Colors.white,
      child: new AnimatedBuilder(
        animation: animationController,
        child: new Container(
          height: 80.0,
          width: 80.0,
          child: new Image.asset('images/StarLogo.png'),
        ),
        builder: (BuildContext context, Widget _widget) {
          return new Transform.rotate(
            angle: animationController.value,
            child: _widget,
          );
        },
      ),
    );
  }
}

Solution

Here my example of rotating image. I don’t know – but maybe it suits for you

AnimationController rotationController;

@override
void initState() {
  rotationController = AnimationController(duration: const Duration(milliseconds: 500), vsync: this);
  super.initState();
}
//...
RotationTransition(
  turns: Tween(begin: 0.0, end: 1.0).animate(rotationController),
  child: ImgButton(...)
//...
rotationController.forward(from: 0.0); // it starts the animation

UPD – how to solve problem with Transform.rotate

In your case all works exactly as you’ve written – it rotates image from 0.0 to 1.0 (it’s default parameters for AnimationController). For full circle you have to set upper parameter to 2 * pi (from math package)

import 'dart:math';
//...
animationController = AnimationController(vsync: this, duration: Duration(seconds: 5), upperBound: pi * 2);

Answered By – Andrey Turkovsky

Answer Checked By – Marie Seifert (FlutterFixes Admin)

Leave a Reply

Your email address will not be published.