If you need to create complex shapes, custom visual effects, or even a signature pad, CustomPainter is the way to go. It gives you complete control over drawing on the canvas.
Example: Drawing a Sun with Rays
This example demonstrates how to use CustomPainter to draw a simple sun with rays:
import 'package:flutter/material.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar(title: Text("Custom Painter Example")), body: Center( child: CustomPaint( size: Size(300, 300), // Canvas size painter: SunPainter(), ), ), ), ); } } class SunPainter extends CustomPainter { @override void paint(Canvas canvas, Size size) { final paint = Paint() ..color = Colors.orange ..style = PaintingStyle.fill; // Draw the sun (circle) final center = Offset(size.width / 2, size.height / 2); final radius = size.width * 0.2; canvas.drawCircle(center, radius, paint); // Draw rays final rayPaint = Paint() ..color = Colors.orangeAccent ..strokeWidth = 4; for (int i = 0; i < 12; i++) { final angle = i * 30.0 * 3.1416 / 180; // Convert to radians final startX = center.dx + radius * 1.2 * cos(angle); final startY = center.dy + radius * 1.2 * sin(angle); final endX = center.dx + radius * 2 * cos(angle); final endY = center.dy + radius * 2 * sin(angle); canvas.drawLine(Offset(startX, startY), Offset(endX, endY), rayPaint); } } @override bool shouldRepaint(covariant CustomPainter oldDelegate) { return false; // No need to repaint for static drawings } }
Explanation:
CustomPainter: Handles the drawing logic on the canvas.
Canvas: The drawing surface where you can draw shapes, lines, text, etc.
Paint: Configures color, stroke width, and style (fill or stroke).
drawCircle and drawLine: Used to draw the sun and its rays.
Use Cases:
Custom progress indicators.
Charts or graphs.
Signature pads.
Game elements.
This method allows for creative freedom and precise control over your Flutter app’s visuals.
Top comments (0)