RotationTransition Widget - Flutter Widget Guide By Flutter Agency

RotationTransition Widget – Flutter Widget Guide By Flutter Agency

Hope you guys are doing well with Flutter. Earlier we have been through AnimatedCrossFade Widget, AnimatedWidgetBaseState Widget, AnimatedPositioned Widget, AnimatedPhysicalModel Widget all these widgets fall under the category of Animated Widget so now this is time for something new called RotationTransition Widget.

Don’t be scared of it we will understand its properties along with an example for the same so let’s get started with it.

First of all, we will understand What is RotationTransition Widget is all about?

RotationTransition Widget is a widget that is basically used to animates rotation of the widget.

Default Constructor of it will have code snippet as below:

RotationTransitionWidget({
   Key key,
   @required Animation<double> turns,
   Alignment alignment: Alignment.center,
   Widget child,
 });

In Above Constructor all the attributes marked with @requuired must not be empty so in this constructor turns must not be empty.

Properties:

  • Key key : This attribute key controls how one widget replaces another widget in the tree.
  • Animation<double> turns: This attribute has a datatype Animation which is used to control the rotation of the child. Depends on the current value it will be rotated. Suppose  If the current value of the turns animation is v, the child will be rotated v * 2 * pi radians before being painted.
  • Alignment alignment : This attribute is used to define the alignment of the origin of the coordinate system around which the rotation occurs, relative to the size of the box.For example, to set the origin of the rotation to top right corner, use an alignment of (1.0, -1.0) or use Alignment.topRight
  • Widget child: This attribute is used to define the widget below this widget in the tree. This widget can only have one child. To layout multiple children, let this widget’s child be a widget such as Row WidgetColumn Widget, or Stack Widget, which have a children’s property, and then provide the children to that widget.

How to use RotationTransition Widget  in Flutter ?

The following code will show you how to make use of RotationTransition Widget.

import 'package:flutter/material.dart';

class RotationTransitionWidget extends StatefulWidget {
  RotationTransitionWidget({Key key}) : super(key: key);

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

class _RotationTransitionWidgetState extends State<RotationTransitionWidget>
    with TickerProviderStateMixin {
  final Tween<double> turnsTween = Tween<double>(
    begin: 1,
    end: 3,
  );

  AnimationController _controller;

  bool _first = true;

  initState() {
    _controller = AnimationController(
      vsync: this,
      duration: const Duration(seconds: 1),
    );
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          RotationTransition(
            turns: turnsTween.animate(_controller),
            child: Container(
              child: Container(
                width: 200,
                height: 200,
                padding: EdgeInsets.all(20),
                child: FlutterLogo(),
              ),
            ),
          ),
          SizedBox(
            height: 20,
          ),
          FlatButton(
            onPressed: () {
              if (_first) {
                _controller.forward();
              } else {
                _controller.reverse();
              }
              _first = !_first;
            },
            child: Text(
              "Click Me!",
              style: Theme.of(context).textTheme.caption.copyWith(
                    fontSize: 20,
                    fontWeight: FontWeight.w600,
                  ),
            ),
          )
        ],
      ),
    );
  }
}

We will get output like below:

Rotation Transition Widget - Flutter Widget Guide By Flutter Agency

Rotation Transition Widget

General Queries on RotationTransition Widget

  • Flutter RotationTransition Widget on Navigate with a half spin

In my app, I’m trying to animate the leading appbar icon to spin when the user navigates to another page. Basically I’m trying to create exactly the same animation as in this video from the material design specification.

I managed to make the icon spin on navigation, using a Hero with a RotationTransition. Currently, however, the icon is spinning a whole circle. I’m quite sure I have to provide another Animation<double> to the turns parameter of RotationTransition, but I got lost in AnimationControllers and vsync.

How do I make the icon spin a half circle? And how to control the spinning speed/duration?

BTW. If there is an easier way to make the icon spin on navigation, suggestions are welcome. Also, in the video, on forward and back navigation the icon spins to the same side. Is that possible, using Navigator.pop()?

Current Code will like below:

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: Hero(
          tag: "mytag",
          child: IconButton(
            icon: Icon(Icons.menu),
            onPressed: null,
          ),
          // Magic happens here
          flightShuttleBuilder: (
            BuildContext flightContext,
            Animation<double> animation,
            HeroFlightDirection flightDirection,
            BuildContext fromHeroContext,
            BuildContext toHeroContext,
          ) {
            return RotationTransition(
              turns: animation,
              child: Material(
                color: Theme.of(context).primaryColor,
                shadowColor: Theme.of(context).accentColor,
                shape: CircleBorder(),
                child: toHeroContext.widget
              ),
            );
          },
        ),
      ),
      body: Center(
        child: RaisedButton(
          child: Text("To second"),
          onPressed: () {
            Navigator.of(context).push(
              PageRouteBuilder(
                pageBuilder:
                  (context, animation, secondaryAnimation) => SecondPage()
              )
            );
          },
        ),
      )
    );
  }

}

class SecondPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: Hero(
          tag: "mytag",
          child: IconButton(
            icon: Icon(Icons.clear),
            onPressed: null,
          ),
        ),
      ),
      body: Center(
        child: RaisedButton(
          child: Text("To first"),
          onPressed: () {
            Navigator.of(context).pop();
          },
        ),
      )
    );
  }
}

Ans: Updated code with an icon that spins half a circle to the same direction on push and pop:

flightShuttleBuilder: (
    BuildContext flightContext,
    Animation<double> animation,
    HeroFlightDirection flightDirection,
    BuildContext fromHeroContext,
    BuildContext toHeroContext,
  ) {
    Animation<double> newAnimation =
      Tween<double>(begin: 0, end: 0.5).animate(animation);

    if (flightDirection == HeroFlightDirection.pop) {
      newAnimation = ReverseAnimation(newAnimation);
    }

    return RotationTransition(
      turns: newAnimation,
      child: Material(
        color: Theme.of(context).primaryColor,
        shadowColor: Theme.of(context).accentColor,
        shape: CircleBorder(),
        child: toHeroContext.widget
      ),
    );
  }

Thanks for being with us.

Still, needs support for Flutter Development?

FlutterAgency.com is our portal Platform dedicated to Flutter Technology and Flutter Developers. The portal is full of cool resources from Flutter like Flutter Widget GuideFlutter ProjectsCode libs and etc.

FlutterAgency.com is one of the most popular online portal dedicated to Flutter Technology and daily thousands of unique visitors come to this portal to enhance their knowledge on Flutter.

Nirali Patel

Written by Nirali Patel

Nirali Patel is a dedicated Flutter developer with over two years of experience, specializing in creating seamless mobile applications using Dart. With a passion for crafting user-centric solutions, Nirali combines technical proficiency with innovative thinking to push the boundaries of mobile app development.

Leave a comment

Your email address will not be published. Required fields are marked *


Discuss Your Project

Connect with Flutter Agency's proficient skilled team for your app development projects across different technologies. We'd love to hear from you! Fill out the form below to discuss your project.

Have Project For Us

Get in Touch

"*" indicates required fields

ready to get started?

Fill out the form below and we will be in touch soon!

"*" indicates required fields