— Flutter, Widget Rotation, Mobile Development — 1 min read
To rotate a widget in Flutter, the Transform
widget comes to our rescue. It enables us to apply various transformations such as rotation, scaling, and translation to its child widget. Specifically, for rotating a widget, we can use the Matrix4.rotationZ
constructor to create a rotation matrix. This matrix represents a 2D rotation about the z-axis, allowing us to achieve the desired visual effect.
Let's dive into the code and see how we can rotate a widget by 45 degrees. Suppose we have a basic Container
widget that we want to rotate. We can achieve this using the following approach:
1Transform.rotate(2 angle: 0.7854, // 45 degrees in radians3 child: Container(4 width: 100,5 height: 100,6 color: Colors.blue,7 child: Center(8 child: Text(9 'Rotated Widget',10 style: TextStyle(color: Colors.white),11 ),12 ),13 ),14)
In the above code snippet, we use the Transform.rotate
widget to rotate the Container
by an angle of 45 degrees (in radians). The value 0.7854
represents 45 degrees in radians, as 180 degrees equals π radians. The Container
contains a blue background with centered text, showcasing the rotated widget.
To simplify the process and make our code more maintainable, we can encapsulate the rotation logic within a custom widget. This way, we can easily reuse the same rotation functionality across the app without duplicating code. Let's create a RotatedWidget
widget that takes in the angle as a parameter and rotates its child accordingly:
1class RotatedWidget extends StatelessWidget {2 final double angle;3 final Widget child;4
5 RotatedWidget({required this.angle, required this.child});6
7 @override8 Widget build(BuildContext context) {9 return Transform.rotate(10 angle: angle,11 child: child,12 );13 }14}
Now, whenever we need to rotate a widget by a specific angle, we can simply use the RotatedWidget
and pass in the desired angle along with the child widget.
With our custom RotatedWidget
in place, let's revisit the earlier example and see how we can utilize it to achieve the same rotation effect:
1RotatedWidget(2 angle: 0.7854,3 child: Container(4 width: 100,5 height: 100,6 color: Colors.blue,7 child: Center(8 child: Text(9 'Rotated Widget',10 style: TextStyle(color: Colors.white),11 ),12 ),13 ),14)
By employing the RotatedWidget
, we improve the reusability and readability of our code while maintaining the ability to apply the 45-degree rotation effortlessly.