Flutter: Matrix4 to rotate a Container by its center?

5,053

Solution 1

I've found the answer and just made this package (to do all kinds of transformations, not only rotate by the center): https://pub.dev/packages/matrix4_transform

var height = 30;
var width = 30;

AnimatedContainer(
   color: Colors.red, 
   width: width, 
   height: height,
   transform:
     Matrix4Transform()
       .rotateDegrees(180, origin: Offset(width/2, height/2))
       .matrix4,
);

Solution 2

There is no need to use a Matrix4 for a simple 180 degrees rotation. Use RotationTransition to wrap your AnimatedContainer instead. RotationTransition takes a turns parameter, which is an Animation<T> whose value can be used to represent the RotationTransition's child widget rotation in radians. This way, you can control your rotation animation via an AnimationController. Check out this example from the Flutter official GitHub to find out more.

Share:
5,053
MarcG
Author by

MarcG

Currently living in São Paulo and Rio de Janeiro - Brazil. I hold both Brazilian and European (Polish) passports. Aeronautical-Mechanical Engineer (Technological Institute of Aeronautics ITA, the "Brazilian MIT"). MBA (PUC-RJ) Software Architect and Developer. Previously C++, but now mostly Dart/Flutter (see https://pub.dev/publishers/glasberg.dev/packages), JavaScript (Typescript) and Java. Love TDD, BDD and Clean Code. Also very interested in Usability and Gamification. Excellent communication skills and technical writing. I program since I was 10 yo. Love travelling, astronomy, science and games (playing and making them). Links: https://github.com/marcglasberg https://www.linkedin.com/in/marcglasberg/ https://medium.com/flutter-community/https-medium-com-marcglasberg-async-redux-33ac5e27d5f6 https://medium.com/flutter-community/i18n-extension-flutter-b966f4c65df9 Patents: https://www.google.com/patents/US7917437 https://www.google.com/patents/US7596530 Fluent English and Portuguese, good Spanish, some French. Come visit Rio and rent my place in AirBnB: https://www.airbnb.com/rooms/13830632 [email protected]

Updated on December 07, 2022

Comments

  • MarcG
    MarcG over 1 year

    I have an AnimatedContainer, and I want to rotate it by 180 degrees, and the origin should be at its center.

    It has a transform parameter that, unfortunately, asks for a Matrix4.

    There is no explanation of Matrix4 in the Flutter documentation: https://api.flutter.dev/flutter/vector_math_64/Matrix4-class.html

    What is the Matrix4 I must use to rotate it by its center?