How to Draw a Rectangle in Flutter
•2 min read
Drawing a rectangle in Flutter can be achieved using the CustomPainter
class or by leveraging built-in widgets like Container
.
Using CustomPainter
The CustomPainter
class allows you to draw custom shapes, including rectangles, on a canvas.
Example
import 'package:flutter/material.dart'; class RectanglePainter extends CustomPainter { @override void paint(Canvas canvas, Size size) { final paint = Paint() ..color = Colors.red ..style = PaintingStyle.fill; canvas.drawRect(Rect.fromLTWH(50, 50, 100, 100), paint); } @override bool shouldRepaint(covariant CustomPainter oldDelegate) => false; } class RectangleWidget extends StatelessWidget { @override Widget build(BuildContext context) { return CustomPaint( size: Size(200, 200), painter: RectanglePainter(), ); } } void main() { runApp(MaterialApp( home: Scaffold( body: Center( child: RectangleWidget(), ), ), )); }
Using a Container
For simpler use cases, you can use a Container
to create a rectangle.
Example
Container( width: 100, height: 100, color: Colors.red, );
By using these methods, you can easily draw rectangles in your Flutter applications.