<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Banatube on Medium]]></title>
        <description><![CDATA[Stories by Banatube on Medium]]></description>
        <link>https://medium.com/@banatube?source=rss-73f4bbebcd9d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*EsEzT_Nqr7GQtg5vkcuZ2Q.png</url>
            <title>Stories by Banatube on Medium</title>
            <link>https://medium.com/@banatube?source=rss-73f4bbebcd9d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 14:06:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@banatube/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Level Up Your Chat Game: How to Find the Best Animated WhatsApp Stickers]]></title>
            <link>https://banatube.medium.com/level-up-your-chat-game-how-to-find-the-best-animated-whatsapp-stickers-71431e4811d2?source=rss-73f4bbebcd9d------2</link>
            <guid isPermaLink="false">https://medium.com/p/71431e4811d2</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[social-media]]></category>
            <category><![CDATA[whatsapp]]></category>
            <category><![CDATA[gif]]></category>
            <category><![CDATA[stickers]]></category>
            <dc:creator><![CDATA[Banatube]]></dc:creator>
            <pubDate>Thu, 07 May 2026 14:00:38 GMT</pubDate>
            <atom:updated>2026-05-07T14:00:38.761Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lNr1w-sXz9i93WAN8cCsog.png" /></figure><p>We’ve all been there. The group chat is popping off, the perfect roast has been delivered, and you’re scrolling through your sticker drawer like a frantic librarian — only to find nothing that quite captures the “sassy yet unbothered” vibe you need.</p><p>Enter <a href="https://www.dlstickers.com/"><strong>dlstickers</strong></a>, a hidden gem of a platform that’s basically a playground for high-quality, animated WhatsApp stickers (GIFs). If you’re ready to graduate from basic emojis to top-tier reactions, here is how to navigate the site and find your new favorite animations.</p><h4>Start with the “Animated GIF” Filter</h4><p>When you land on the homepage, don’t just wander aimlessly. The site is packed with content, but if you specifically want things that move, look at the top navigation bar.</p><ul><li><strong>Pro Tip:</strong> Click on the <strong>“Animated GIF”</strong> tab. This filters out the static images and brings you straight to the stickers that wiggle, dance, and face-palm.</li></ul><h4>Use the Search Bar (Be Specific!)</h4><p>Located at the top right, the search bar is your best friend. Instead of searching for “sad,” try searching for the specific character or meme style you like.</p><ul><li><strong>Characters:</strong> Search for “Sailor Moon,” “BT21,” or “Homer Simpson.”</li><li><strong>Vibes:</strong> Try “Sassy,” “Overwhelmed,” or “Sweaty” to find those niche reaction GIFs that hit home.</li></ul><h4>Explore by Category</h4><p>If you’re just browsing for “sticker inspiration,” scroll down to the <strong>Categories</strong> section in the footer or use the “Categories” dropdown menu. The site organizes stickers into helpful buckets like:</p><ul><li><strong>Reactions:</strong> For when words fail you.</li><li><strong>Animals:</strong> Because a “Vampire Cat” is always relevant.</li><li><strong>TV &amp; Movies:</strong> To find your favorite iconic pop culture moments.</li></ul><h4>Check the “Related Stickers” Section</h4><p>Once you find a sticker you like — say, the legendary <strong>“Sassy hair flip”</strong> — don’t stop there.</p><p>When you click on an individual sticker page, distickers provides a <strong>“Related Stickers”</strong> grid at the bottom. This is the ultimate rabbit hole. If you like one sassy toddler, the algorithm will show you three more kids sipping juice or looking confused, helping you build a themed “sticker pack” of your own.</p><blockquote><strong><em>Why it matters:</em></strong><em> Building a consistent “sticker brand” in your chats makes your reactions more recognizable and, frankly, much funnier.</em></blockquote><h4>Quick Stats: Know What You’re Downloading</h4><p>Before you hit that download button, check the <strong>Image Information</strong> box on the sticker page. It tells you:</p><ul><li><strong>Format:</strong> (Usually GIF for animated stickers).</li><li><strong>Dimensions:</strong> Ensures it won’t look blurry in the chat.</li><li><strong>Size:</strong> Important if you’re trying to save data!</li></ul><h4>How to Get Them Into WhatsApp</h4><p>According to the site’s FAQ, you don’t necessarily need a third-party “sticker maker” app anymore. WhatsApp now allows you to <strong>import images directly</strong> into your sticker gallery. Simply download the GIF from distickers, open your WhatsApp sticker tray, and use the “create” or “+” feature to turn that fresh download into a permanent part of your arsenal.</p><h4>Final Thoughts</h4><p>In the world of digital communication, a well-timed sticker is worth a thousand words. Whether you’re feeling like a “Nervous Sailor Moon” or a “Confused Toddler,” platforms like distickers make it easy to find your voice.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=71431e4811d2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Flutter CustomPainter: The Complete Developer’s Guide]]></title>
            <link>https://banatube.medium.com/mastering-flutter-custompainter-the-complete-developers-guide-f9b1e8575e6c?source=rss-73f4bbebcd9d------2</link>
            <guid isPermaLink="false">https://medium.com/p/f9b1e8575e6c</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[ui-ux-design]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[animation]]></category>
            <category><![CDATA[custom-graphics]]></category>
            <dc:creator><![CDATA[Banatube]]></dc:creator>
            <pubDate>Tue, 05 Aug 2025 15:33:34 GMT</pubDate>
            <atom:updated>2025-08-05T15:35:58.042Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Transform your Flutter apps with stunning custom graphics, animations, and visualizations</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jkp3IsxqVRlp6TMIQ4byQQ.png" /></figure><p>CustomPainter is one of Flutter’s most powerful yet underutilized features. It’s the gateway to creating stunning custom graphics, smooth animations, and unique visual experiences that set your app apart from the competition. In this comprehensive guide, we’ll take you from CustomPainter novice to expert.</p><h4>Table of Contents</h4><ol><li>What is CustomPainter?</li><li>When to Use CustomPainter</li><li>Core Concepts</li><li>Your First CustomPainter</li><li>Paint and Canvas Fundamentals</li><li>Drawing Basic Shapes</li><li>Working with Colors and Gradients</li><li>Mastering Paths</li><li>Custom Text Rendering</li><li>Animations with CustomPainter</li><li>Real-World Projects</li><li>Performance Tips</li><li>Advanced Techniques</li></ol><h4>What is CustomPainter?</h4><p>CustomPainter is an abstract class in Flutter that allows you to create custom graphics by drawing directly on a canvas. Think of it as having a digital paintbrush with unlimited creative possibilities.</p><pre>class MyCustomPainter extends CustomPainter {<br>  @override<br>  void paint(Canvas canvas, Size size) {<br>    // Your drawing magic happens here<br>  }<br><br>  @override<br>  bool shouldRepaint(CustomPainter oldDelegate) {<br>    return false; // Optimize repainting<br>  }<br>}</pre><p>CustomPainter gives you pixel-level control over your UI, enabling you to create:</p><ul><li><strong>Custom shapes and graphics</strong></li><li><strong>Complex animations</strong></li><li><strong>Data visualizations</strong></li><li><strong>Interactive elements</strong></li><li><strong>Unique visual effects</strong></li></ul><h4>When to Use CustomPainter</h4><h4>✅ Perfect Use Cases</h4><ul><li><strong>Unique UI elements</strong> that don’t exist in Flutter’s widget library</li><li><strong>High-performance animations</strong> requiring 60fps smooth rendering</li><li><strong>Data visualizations</strong> like charts, graphs, and dashboards</li><li><strong>Custom icons and illustrations</strong></li><li><strong>Gaming elements</strong> and interactive graphics</li><li><strong>Complex geometric shapes</strong></li></ul><h4>❌ Avoid CustomPainter When</h4><ul><li>Existing Flutter widgets can achieve the same result</li><li>Simple styling changes (use themes instead)</li><li>Performance isn’t critical</li><li>Maintenance complexity outweighs benefits</li></ul><h4>Core Concepts</h4><p>The Trinity: Canvas, Paint &amp; Size</p><p>Understanding these three core concepts is crucial for CustomPainter mastery:</p><p><strong>Canvas</strong>: Your digital drawing surface <strong>Paint</strong>: Your brush with style properties<br> <strong>Size</strong>: The available drawing dimensions</p><h4>Coordinate System</h4><p>Flutter uses a standard 2D coordinate system:</p><ul><li>Origin (0,0) is at the top-left corner</li><li>X-axis increases rightward</li><li>Y-axis increases downward</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/1*4degd2j2ZxDTSIFBUdptgQ.png" /><figcaption>Coordinate System</figcaption></figure><h4>Your First CustomPainter</h4><p>Let’s start with a simple circle to understand the basics:</p><pre>import &#39;package:flutter/material.dart&#39;;<br><br>class SimpleCirclePainter extends CustomPainter {<br>  @override<br>  void paint(Canvas canvas, Size size) {<br>    final paint = Paint()<br>      ..color = Colors.blue<br>      ..style = PaintingStyle.fill;<br><br>    final center = Offset(size.width / 2, size.height / 2);<br>    final radius = size.width * 0.4;<br>    <br>    canvas.drawCircle(center, radius, paint);<br>  }<br><br>  @override<br>  bool shouldRepaint(CustomPainter oldDelegate) =&gt; false;<br>}<br><br>// Usage<br>class CircleWidget extends StatelessWidget {<br>  const CircleWidget({super.key});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return PulsingCircleWidget();<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r_lTQk9CH8Zz6Wmik89AMA.png" /><figcaption>Simple Circle Painter</figcaption></figure><h4>Adding a Border</h4><pre>class CircleWithBorderPainter extends CustomPainter {<br>  @override<br>  void paint(Canvas canvas, Size size) {<br>    final center = Offset(size.width / 2, size.height / 2);<br>    final radius = size.width * 0.4;<br><br>    // Fill<br>    final fillPaint = Paint()<br>      ..color = Colors.blue<br>      ..style = PaintingStyle.fill;<br>    <br>    canvas.drawCircle(center, radius, fillPaint);<br><br>    // Border<br>    final borderPaint = Paint()<br>      ..color = Colors.black<br>      ..strokeWidth = 4.0<br>      ..style = PaintingStyle.stroke;<br>    <br>    canvas.drawCircle(center, radius, borderPaint);<br>  }<br><br>  @override<br>  bool shouldRepaint(CustomPainter oldDelegate) =&gt; false;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qB3FzBGJcAfrEtIl655eZA.png" /><figcaption>Circle With Border Painter</figcaption></figure><h4>Paint and Canvas Fundamentals</h4><h4>Paint Properties Deep Dive</h4><pre>final paint = Paint()<br>  ..color = Colors.blue                    // Color<br>  ..strokeWidth = 2.0                     // Line thickness<br>  ..style = PaintingStyle.fill            // Fill or stroke<br>  ..strokeCap = StrokeCap.round          // Line endings<br>  ..strokeJoin = StrokeJoin.round        // Line joints<br>  ..isAntiAlias = true                   // Smooth edges<br>  ..blendMode = BlendMode.multiply       // Blend with background<br>  ..maskFilter = MaskFilter.blur(        // Blur effect<br>    BlurStyle.normal, <br>    4.0<br>  );</pre><h4>Canvas Drawing Methods</h4><pre>// Basic shapes<br>canvas.drawCircle(center, radius, paint);<br>canvas.drawRect(rect, paint);<br>canvas.drawLine(start, end, paint);<br>canvas.drawPoints(PointMode.points, points, paint);<br><br>// Complex shapes<br>canvas.drawPath(path, paint);<br>canvas.drawRRect(roundedRect, paint);<br>canvas.drawOval(rect, paint);<br><br>// Arcs and sectors<br>canvas.drawArc(rect, startAngle, sweepAngle, useCenter, paint);<br><br>// Images and text<br>canvas.drawImage(image, offset, paint);<br>canvas.drawParagraph(paragraph, offset);</pre><h4>Drawing Basic Shapes</h4><h4>Comprehensive Shapes Example</h4><pre>class BasicShapesPainter extends CustomPainter {<br>  @override<br>  void paint(Canvas canvas, Size size) {<br>    // 1. Filled Circle<br>    final circlePaint = Paint()<br>      ..color = Colors.red<br>      ..style = PaintingStyle.fill;<br>    <br>    canvas.drawCircle(<br>      Offset(size.width * 0.2, size.height * 0.2),<br>      40,<br>      circlePaint,<br>    );<br><br>    // 2. Stroked Rectangle<br>    final rectPaint = Paint()<br>      ..color = Colors.green<br>      ..strokeWidth = 3.0<br>      ..style = PaintingStyle.stroke;<br>    <br>    canvas.drawRect(<br>      Rect.fromLTWH(size.width * 0.6, size.height * 0.1, 80, 60),<br>      rectPaint,<br>    );<br><br>    // 3. Rounded Rectangle<br>    final roundedRectPaint = Paint()<br>      ..color = Colors.purple<br>      ..style = PaintingStyle.fill;<br>    <br>    canvas.drawRRect(<br>      RRect.fromRectAndRadius(<br>        Rect.fromLTWH(size.width * 0.1, size.height * 0.4, 100, 60),<br>        Radius.circular(15),<br>      ),<br>      roundedRectPaint,<br>    );<br><br>    // 4. Line with custom caps<br>    final linePaint = Paint()<br>      ..color = Colors.orange<br>      ..strokeWidth = 8.0<br>      ..strokeCap = StrokeCap.round;<br>    <br>    canvas.drawLine(<br>      Offset(50, size.height * 0.7),<br>      Offset(size.width - 50, size.height * 0.7),<br>      linePaint,<br>    );<br><br>    // 5. Points (dots)<br>    final pointsPaint = Paint()<br>      ..color = Colors.blue<br>      ..strokeWidth = 12.0<br>      ..strokeCap = StrokeCap.round;<br>    <br>    final points = &lt;Offset&gt;[<br>      Offset(size.width * 0.2, size.height * 0.85),<br>      Offset(size.width * 0.4, size.height * 0.8),<br>      Offset(size.width * 0.6, size.height * 0.9),<br>      Offset(size.width * 0.8, size.height * 0.85),<br>    ];<br>    <br>    canvas.drawPoints(PointMode.points, points, pointsPaint);<br>  }<br><br>  @override<br>  bool shouldRepaint(CustomPainter oldDelegate) =&gt; false;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OaxnBGVkOHE9G3YXIVmlHQ.png" /><figcaption>Basic Shapes Painter</figcaption></figure><h4>Working with Arcs</h4><pre>import &#39;dart:math&#39; as math;<br><br>class ArcsPainter extends CustomPainter {<br>  @override<br>  void paint(Canvas canvas, Size size) {<br>    final center = Offset(size.width / 2, size.height / 2);<br>    final radius = size.width * 0.3;<br>    final rect = Rect.fromCircle(center: center, radius: radius);<br><br>    // Arc (portion of circle circumference)<br>    final arcPaint = Paint()<br>      ..color = Colors.blue<br>      ..strokeWidth = 8.0<br>      ..style = PaintingStyle.stroke<br>      ..strokeCap = StrokeCap.round;<br>    <br>    canvas.drawArc(<br>      rect,<br>      0,              // Start angle (radians)<br>      math.pi,        // Sweep angle (180 degrees)<br>      false,          // useCenter: false = arc<br>      arcPaint,<br>    );<br><br>    // Pie sector<br>    final sectorPaint = Paint()<br>      ..color = Colors.red.withValues(alpha: 0.7)<br>      ..style = PaintingStyle.fill;<br>    <br>    canvas.drawArc(<br>      rect,<br>      math.pi,        // Start at 180 degrees<br>      math.pi / 2,    // Sweep 90 degrees<br>      true,           // useCenter: true = pie slice<br>      sectorPaint,<br>    );<br>  }<br><br>  @override<br>  bool shouldRepaint(CustomPainter oldDelegate) =&gt; false;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZtUP_WNIcD-07Ul_QeDA4A.png" /><figcaption>Arcs Painter</figcaption></figure><h4>Working with Colors and Gradients</h4><h4>Linear Gradients</h4><pre>class LinearGradientPainter extends CustomPainter {<br>  @override<br>  void paint(Canvas canvas, Size size) {<br>    final rect = Rect.fromLTWH(0, 0, size.width, size.height);<br>    <br>    final gradient = LinearGradient(<br>      begin: Alignment.topLeft,<br>      end: Alignment.bottomRight,<br>      colors: [<br>        Colors.purple,<br>        Colors.blue,<br>        Colors.teal,<br>      ],<br>      stops: [0.0, 0.5, 1.0],<br>    );<br><br>    final paint = Paint()<br>      ..shader = gradient.createShader(rect);<br><br>    canvas.drawRect(rect, paint);<br>  }<br><br>  @override<br>  bool shouldRepaint(CustomPainter oldDelegate) =&gt; false;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t2J6aWstMM4tBLvll0jkmQ.png" /><figcaption>Linear Gradient Painter</figcaption></figure><h4>Radial Gradients</h4><pre>class RadialGradientPainter extends CustomPainter {<br>  @override<br>  void paint(Canvas canvas, Size size) {<br>    final center = Offset(size.width / 2, size.height / 2);<br>    final radius = size.width * 0.4;<br><br>    final gradient = RadialGradient(<br>      center: Alignment.center,<br>      radius: 1.0,<br>      colors: [<br>        Colors.yellow,<br>        Colors.orange,<br>        Colors.red,<br>        Colors.purple,<br>      ],<br>      stops: [0.0, 0.3, 0.7, 1.0],<br>    );<br><br>    final rect = Rect.fromLTWH(0, 0, size.width, size.height);<br>    final paint = Paint()<br>      ..shader = gradient.createShader(rect);<br><br>    canvas.drawCircle(center, radius, paint);<br>  }<br><br>  @override<br>  bool shouldRepaint(CustomPainter oldDelegate) =&gt; false;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y1lakY2rzLa3yda9r5_XoQ.png" /><figcaption>Radial Gradient Painter</figcaption></figure><h4>Sweep Gradients</h4><pre>class SweepGradientPainter extends CustomPainter {<br>  @override<br>  void paint(Canvas canvas, Size size) {<br>    final center = Offset(size.width / 2, size.height / 2);<br>    final radius = size.width * 0.4;<br><br>    final gradient = SweepGradient(<br>      center: Alignment.center,<br>      startAngle: 0.0,<br>      endAngle: math.pi * 2,<br>      colors: [<br>        Colors.red,<br>        Colors.yellow,<br>        Colors.green,<br>        Colors.blue,<br>        Colors.purple,<br>        Colors.red,<br>      ],<br>    );<br><br>    final rect = Rect.fromLTWH(0, 0, size.width, size.height);<br>    final paint = Paint()<br>      ..shader = gradient.createShader(rect);<br><br>    canvas.drawCircle(center, radius, paint);<br>  }<br><br>  @override<br>  bool shouldRepaint(CustomPainter oldDelegate) =&gt; false;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DzOfoiX6Y6pkDPYrdKadUg.png" /><figcaption>Sweep Gradient Painter</figcaption></figure><h4>Mastering Paths</h4><p>Paths are the key to creating complex, custom shapes. Think of a path as a series of drawing instructions.</p><h4>Basic Path Operations</h4><pre>class BasicPathPainter extends CustomPainter {<br>  @override<br>  void paint(Canvas canvas, Size size) {<br>    final paint = Paint()<br>      ..color = Colors.blue<br>      ..strokeWidth = 3.0<br>      ..style = PaintingStyle.stroke;<br><br>    final path = Path();<br><br>    // Move to starting point (without drawing)<br>    path.moveTo(50, 50);<br><br>    // Draw lines<br>    path.lineTo(150, 50);   // Horizontal line<br>    path.lineTo(200, 150);  // Diagonal line<br>    path.lineTo(100, 200);  // Another diagonal<br>    path.lineTo(50, 100);   // Back towards start<br><br>    // Close the path (connects to starting point)<br>    path.close();<br><br>    canvas.drawPath(path, paint);<br>  }<br><br>  @override<br>  bool shouldRepaint(CustomPainter oldDelegate) =&gt; false;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PyYYMKJh2yS9j0CIfhhqcg.png" /><figcaption>Basic Path Painter</figcaption></figure><h4>Bezier Curves</h4><pre>class BezierCurvesPainter extends CustomPainter {<br>  @override<br>  void paint(Canvas canvas, Size size) {<br>    final paint = Paint()<br>      ..color = Colors.purple<br>      ..strokeWidth = 4.0<br>      ..style = PaintingStyle.stroke;<br><br>    final path = Path();<br><br>    // Quadratic Bezier curve<br>    path.moveTo(50, size.height * 0.8);<br>    path.quadraticBezierTo(<br>      size.width * 0.5, 50,           // Control point<br>      size.width - 50, size.height * 0.8, // End point<br>    );<br><br>    canvas.drawPath(path, paint);<br><br>    // Cubic Bezier curve<br>    final path2 = Path();<br>    paint.color = Colors.red;<br>    <br>    path2.moveTo(50, size.height * 0.5);<br>    path2.cubicTo(<br>      size.width * 0.25, 100,        // First control point<br>      size.width * 0.75, 300,        // Second control point<br>      size.width - 50, size.height * 0.5, // End point<br>    );<br><br>    canvas.drawPath(path2, paint);<br>  }<br><br>  @override<br>  bool shouldRepaint(CustomPainter oldDelegate) =&gt; false;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OWIFfgxmSepFqBzFfEYYUg.png" /><figcaption>Bezier Curves Painter</figcaption></figure><h4>Creating a Star Shape</h4><pre>import &#39;dart:math&#39; as math;<br><br>class StarPainter extends CustomPainter {<br>  final int points;<br>  final double innerRadius;<br>  final double outerRadius;<br><br>  StarPainter({<br>    this.points = 5,<br>    this.innerRadius = 40,<br>    this.outerRadius = 80,<br>  });<br><br>  @override<br>  void paint(Canvas canvas, Size size) {<br>    final center = Offset(size.width / 2, size.height / 2);<br>    final path = Path();<br><br>    for (int i = 0; i &lt; points * 2; i++) {<br>      final angle = (i * math.pi) / points;<br>      final radius = i.isEven ? outerRadius : innerRadius;<br>      final x = center.dx + radius * math.cos(angle - math.pi / 2);<br>      final y = center.dy + radius * math.sin(angle - math.pi / 2);<br><br>      if (i == 0) {<br>        path.moveTo(x, y);<br>      } else {<br>        path.lineTo(x, y);<br>      }<br>    }<br><br>    path.close();<br><br>    // Fill the star<br>    final fillPaint = Paint()<br>      ..color = Colors.yellow<br>      ..style = PaintingStyle.fill;<br>    <br>    canvas.drawPath(path, fillPaint);<br><br>    // Add border<br>    final strokePaint = Paint()<br>      ..color = Colors.orange<br>      ..strokeWidth = 3.0<br>      ..style = PaintingStyle.stroke;<br>    <br>    canvas.drawPath(path, strokePaint);<br>  }<br><br>  @override<br>  bool shouldRepaint(CustomPainter oldDelegate) =&gt; false;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vOKYPD0EL8P46EEUD12KAA.png" /><figcaption>Star Painter</figcaption></figure><h4>Custom Text Rendering</h4><h4>Basic Text Drawing</h4><pre>class CustomTextPainter extends CustomPainter {<br>  final String text;<br>  <br>  CustomTextPainter(this.text);<br><br>  @override<br>  void paint(Canvas canvas, Size size) {<br>    final textStyle = TextStyle(<br>      color: Colors.black,<br>      fontSize: 24,<br>      fontWeight: FontWeight.bold,<br>      letterSpacing: 2.0,<br>    );<br><br>    final textSpan = TextSpan(<br>      text: text,<br>      style: textStyle,<br>    );<br><br>    final textPainter = TextPainter(<br>      text: textSpan,<br>      textDirection: TextDirection.ltr,<br>      textAlign: TextAlign.center,<br>    );<br><br>    textPainter.layout(<br>      minWidth: 0,<br>      maxWidth: size.width,<br>    );<br><br>    final offset = Offset(<br>      (size.width - textPainter.width) / 2,<br>      (size.height - textPainter.height) / 2,<br>    );<br><br>    textPainter.paint(canvas, offset);<br>  }<br><br>  @override<br>  bool shouldRepaint(CustomPainter oldDelegate) =&gt; true;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jrTJ1eMB8Q5LghUMI0EwHQ.png" /><figcaption>Custom Text Painter</figcaption></figure><h4>Curved Text Effect</h4><pre>class CurvedTextPainter extends CustomPainter {<br>  final String text;<br>  final double radius;<br>  <br>  CurvedTextPainter(this.text, {this.radius = 100});<br><br>  @override<br>  void paint(Canvas canvas, Size size) {<br>    final center = Offset(size.width / 2, size.height / 2);<br>    <br>    for (int i = 0; i &lt; text.length; i++) {<br>      final char = text[i];<br>      final angle = (i - text.length / 2) * 0.2; // Adjust spacing<br>      <br>      canvas.save();<br>      canvas.translate(center.dx, center.dy);<br>      canvas.rotate(angle);<br>      canvas.translate(0, -radius);<br>      <br>      final textSpan = TextSpan(<br>        text: char,<br>        style: TextStyle(<br>          fontSize: 20,<br>          color: Colors.blue,<br>          fontWeight: FontWeight.bold,<br>        ),<br>      );<br>      <br>      final textPainter = TextPainter(<br>        text: textSpan,<br>        textDirection: TextDirection.ltr,<br>      );<br>      <br>      textPainter.layout();<br>      textPainter.paint(<br>        canvas, <br>        Offset(-textPainter.width / 2, 0)<br>      );<br>      <br>      canvas.restore();<br>    }<br>  }<br><br>  @override<br>  bool shouldRepaint(CustomPainter oldDelegate) =&gt; false;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*82WMr4vIkHjlzJnnhTVtjA.png" /><figcaption>Curved Text Painter</figcaption></figure><h4>Multi-Style Text</h4><pre>class RichTextPainter extends CustomPainter {<br>  @override<br>  void paint(Canvas canvas, Size size) {<br>    final textSpan = TextSpan(<br>      children: [<br>        TextSpan(<br>          text: &#39;Hello &#39;,<br>          style: TextStyle(<br>            fontSize: 24,<br>            color: Colors.blue,<br>            fontWeight: FontWeight.normal,<br>          ),<br>        ),<br>        TextSpan(<br>          text: &#39;Beautiful &#39;,<br>          style: TextStyle(<br>            fontSize: 28,<br>            color: Colors.red,<br>            fontWeight: FontWeight.bold,<br>            fontStyle: FontStyle.italic,<br>          ),<br>        ),<br>        TextSpan(<br>          text: &#39;World!&#39;,<br>          style: TextStyle(<br>            fontSize: 24,<br>            color: Colors.green,<br>            fontWeight: FontWeight.normal,<br>            decoration: TextDecoration.underline,<br>          ),<br>        ),<br>      ],<br>    );<br><br>    final textPainter = TextPainter(<br>      text: textSpan,<br>      textDirection: TextDirection.ltr,<br>      textAlign: TextAlign.center,<br>    );<br><br>    textPainter.layout(maxWidth: size.width);<br>    <br>    final offset = Offset(<br>      (size.width - textPainter.width) / 2,<br>      (size.height - textPainter.height) / 2,<br>    );<br><br>    textPainter.paint(canvas, offset);<br>  }<br><br>  @override<br>  bool shouldRepaint(CustomPainter oldDelegate) =&gt; false;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ea8mFNeJt4mqON6r7e2n8A.png" /><figcaption>Rich Text Painter</figcaption></figure><h4>Animations with CustomPainter</h4><h4>Pulsing Circle Animation</h4><pre>class PulsingCirclePainter extends CustomPainter {<br>  final double animationValue;<br><br>  PulsingCirclePainter(this.animationValue);<br><br>  @override<br>  void paint(Canvas canvas, Size size) {<br>    final center = Offset(size.width / 2, size.height / 2);<br>    final baseRadius = size.width * 0.2;<br><br>    // Create multiple pulsing circles<br>    for (int i = 0; i &lt; 3; i++) {<br>      final delay = i * 0.3;<br>      final adjustedValue = ((animationValue - delay) % 1.0).clamp(0.0, 1.0);<br>      final radius = baseRadius + (baseRadius * adjustedValue);<br>      final opacity = 1.0 - adjustedValue;<br><br>      final paint = Paint()<br>        ..color = Colors.blue.withValues(alpha: opacity)<br>        ..style = PaintingStyle.stroke<br>        ..strokeWidth = 3.0;<br><br>      canvas.drawCircle(center, radius, paint);<br>    }<br>  }<br><br>  @override<br>  bool shouldRepaint(CustomPainter oldDelegate) {<br>    return oldDelegate is PulsingCirclePainter &amp;&amp;<br>        oldDelegate.animationValue != animationValue;<br>  }<br>}<br><br>// Widget implementation<br>class PulsingCircleWidget extends StatefulWidget {<br>  const PulsingCircleWidget({super.key});<br><br>  @override<br>  State&lt;PulsingCircleWidget&gt; createState() =&gt; _PulsingCircleWidgetState();<br>}<br><br>class _PulsingCircleWidgetState extends State&lt;PulsingCircleWidget&gt;<br>    with SingleTickerProviderStateMixin {<br>  late AnimationController _controller;<br><br>  @override<br>  void initState() {<br>    super.initState();<br>    _controller = AnimationController(<br>      duration: Duration(seconds: 2),<br>      vsync: this,<br>    )..repeat();<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return AnimatedBuilder(<br>      animation: _controller,<br>      builder: (context, child) {<br>        return CustomPaint(<br>          painter: PulsingCirclePainter(_controller.value),<br>          size: Size(200, 200),<br>        );<br>      },<br>    );<br>  }<br><br>  @override<br>  void dispose() {<br>    _controller.dispose();<br>    super.dispose();<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/346/1*WPEKkDqi5ZQ8CqmTv-2CTw.gif" /><figcaption>Pulsing Circle Painter</figcaption></figure><h4>Animated Wave Effect</h4><pre>import &#39;dart:math&#39; as math;<br><br>class WavePainter extends CustomPainter {<br>  final double animationValue;<br>  final int waveCount;<br>  <br>  WavePainter(this.animationValue, {this.waveCount = 3});<br><br>  @override<br>  void paint(Canvas canvas, Size size) {<br>    for (int wave = 0; wave &lt; waveCount; wave++) {<br>      final paint = Paint()<br>        ..color = Colors.blue.withOpacity(0.3 + (wave * 0.2))<br>        ..style = PaintingStyle.fill;<br><br>      final path = Path();<br>      final waveHeight = 40.0 + (wave * 10);<br>      final frequency = 2.0 + (wave * 0.5);<br>      final phase = animationValue * 2 * math.pi + (wave * math.pi / 4);<br>      <br>      path.moveTo(0, size.height);<br>      <br>      for (double x = 0; x &lt;= size.width; x += 2) {<br>        final y = size.height * 0.5 + <br>                 math.sin((x / size.width * frequency * 2 * math.pi) + phase) * <br>                 waveHeight;<br>        path.lineTo(x, y);<br>      }<br>      <br>      path.lineTo(size.width, size.height);<br>      path.close();<br>      <br>      canvas.drawPath(path, paint);<br>    }<br>  }<br><br>  @override<br>  bool shouldRepaint(CustomPainter oldDelegate) {<br>    return oldDelegate is WavePainter &amp;&amp; <br>           oldDelegate.animationValue != animationValue;<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/344/1*fcR1-LV3lIYLLXEZtNtLRg.gif" /><figcaption>Wave Painter</figcaption></figure><h4>Real-World Projects</h4><h4>Project 1: Animated Bar Chart</h4><pre>class AnimatedBarChartPainter extends CustomPainter {<br>  final List&lt;double&gt; data;<br>  final double animationValue;<br>  final List&lt;String&gt; labels;<br><br>  AnimatedBarChartPainter({<br>    required this.data,<br>    required this.animationValue,<br>    required this.labels,<br>  });<br><br>  @override<br>  void paint(Canvas canvas, Size size) {<br>    if (data.isEmpty) return;<br><br>    final maxValue = data.reduce(math.max);<br>    final barWidth = (size.width - 40) / (data.length * 2 - 1);<br>    final chartHeight = size.height - 60; // Reserve space for labels<br><br>    for (int i = 0; i &lt; data.length; i++) {<br>      final barHeight = (data[i] / maxValue) * chartHeight * animationValue;<br>      final x = 20 + (i * barWidth * 2);<br>      final y = size.height - 40 - barHeight;<br><br>      // Bar gradient<br>      final gradient = LinearGradient(<br>        begin: Alignment.topCenter,<br>        end: Alignment.bottomCenter,<br>        colors: [<br>          Colors.blue.shade300,<br>          Colors.blue.shade700,<br>        ],<br>      );<br><br>      final paint = Paint()<br>        ..shader = gradient.createShader(<br>            Rect.fromLTWH(x, y, barWidth, barHeight)<br>        );<br><br>      // Draw bar with rounded top<br>      final path = Path()<br>        ..moveTo(x, y + 10)<br>        ..quadraticBezierTo(x, y, x + 10, y)<br>        ..lineTo(x + barWidth - 10, y)<br>        ..quadraticBezierTo(x + barWidth, y, x + barWidth, y + 10)<br>        ..lineTo(x + barWidth, size.height - 40)<br>        ..lineTo(x, size.height - 40)<br>        ..close();<br><br>      canvas.drawPath(path, paint);<br><br>      // Draw value on top of bar<br>      if (animationValue &gt; 0.8) {<br>        final textSpan = TextSpan(<br>          text: data[i].toInt().toString(),<br>          style: TextStyle(<br>            color: Colors.black87,<br>            fontSize: 12,<br>            fontWeight: FontWeight.bold,<br>          ),<br>        );<br><br>        final textPainter = TextPainter(<br>          text: textSpan,<br>          textDirection: TextDirection.ltr,<br>        );<br><br>        textPainter.layout();<br>        textPainter.paint(<br>          canvas,<br>          Offset(<br>            x + barWidth / 2 - textPainter.width / 2,<br>            y - 25,<br>          ),<br>        );<br>      }<br><br>      // Draw labels<br>      if (i &lt; labels.length) {<br>        final labelSpan = TextSpan(<br>          text: labels[i],<br>          style: TextStyle(<br>            color: Colors.black54,<br>            fontSize: 10,<br>          ),<br>        );<br><br>        final labelPainter = TextPainter(<br>          text: labelSpan,<br>          textDirection: TextDirection.ltr,<br>        );<br><br>        labelPainter.layout();<br>        labelPainter.paint(<br>          canvas,<br>          Offset(<br>            x + barWidth / 2 - labelPainter.width / 2,<br>            size.height - 20,<br>          ),<br>        );<br>      }<br>    }<br>  }<br><br>  @override<br>  bool shouldRepaint(CustomPainter oldDelegate) {<br>    return oldDelegate is AnimatedBarChartPainter &amp;&amp;<br>        (oldDelegate.animationValue != animationValue ||<br>            !listEquals(oldDelegate.data, data));<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/344/1*DocoS3vEvybGZgavux5shA.gif" /><figcaption>Animated Bar Chart Painter</figcaption></figure><h4>Project 2: Interactive Drawing Canvas</h4><pre>class DrawingPainter extends CustomPainter {<br>  final List&lt;DrawingPath&gt; paths;<br><br>  DrawingPainter(this.paths);<br><br>  @override<br>  void paint(Canvas canvas, Size size) {<br>    for (final drawingPath in paths) {<br>      final paint = Paint()<br>        ..color = drawingPath.color<br>        ..strokeWidth = drawingPath.strokeWidth<br>        ..strokeCap = StrokeCap.round<br>        ..strokeJoin = StrokeJoin.round<br>        ..style = PaintingStyle.stroke;<br><br>      canvas.drawPath(drawingPath.path, paint);<br>    }<br>  }<br><br>  @override<br>  bool shouldRepaint(CustomPainter oldDelegate) {<br>    return true;<br>  }<br>}<br><br>class DrawingPath {<br>  final Path path;<br>  final Color color;<br>  final double strokeWidth;<br><br>  DrawingPath({<br>    required this.path,<br>    required this.color,<br>    required this.strokeWidth,<br>  });<br>}<br><br>class DrawingCanvas extends StatefulWidget {<br>  const DrawingCanvas({super.key});<br><br>  @override<br>  State&lt;DrawingCanvas&gt; createState() =&gt; _DrawingCanvasState();<br>}<br><br>class _DrawingCanvasState extends State&lt;DrawingCanvas&gt; {<br>  List&lt;DrawingPath&gt; paths = [];<br>  Color currentColor = Colors.black;<br>  double currentStrokeWidth = 3.0;<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Column(<br>      children: [<br>        // Color and stroke width controls<br>        SizedBox(<br>          height: 60,<br>          child: Row(<br>            children: [<br>              // Color picker<br>              Expanded(<br>                child: ListView(<br>                  scrollDirection: Axis.horizontal,<br>                  children: [<br>                    Colors.black,<br>                    Colors.red,<br>                    Colors.blue,<br>                    Colors.green,<br>                    Colors.purple,<br>                    Colors.orange,<br>                  ].map((color) =&gt;<br>                      GestureDetector(<br>                        onTap: () =&gt; setState(() =&gt; currentColor = color),<br>                        child: Container(<br>                          width: 40,<br>                          height: 40,<br>                          margin: EdgeInsets.all(5),<br>                          decoration: BoxDecoration(<br>                            color: color,<br>                            shape: BoxShape.circle,<br>                            border: currentColor == color<br>                                ? Border.all(color: Colors.grey, width: 3)<br>                                : null,<br>                          ),<br>                        ),<br>                      ),<br>                  ).toList(),<br>                ),<br>              ),<br>              // Clear button<br>              IconButton(<br>                icon: Icon(Icons.clear),<br>                onPressed: () =&gt; setState(() =&gt; paths.clear()),<br>              ),<br>            ],<br>          ),<br>        ),<br>        // Drawing area<br>        Expanded(<br>          child: SizedBox(<br>            width: double.infinity,<br>            child: GestureDetector(<br>              onPanStart: (details) {<br>                final path = Path();<br>                path.moveTo(<br>                  details.localPosition.dx,<br>                  details.localPosition.dy,<br>                );<br><br>                setState(() {<br>                  paths.add(DrawingPath(<br>                    path: path,<br>                    color: currentColor,<br>                    strokeWidth: currentStrokeWidth,<br>                  ));<br>                });<br>              },<br>              onPanUpdate: (details) {<br>                setState(() {<br>                  paths.last.path.lineTo(<br>                    details.localPosition.dx,<br>                    details.localPosition.dy,<br>                  );<br>                });<br>              },<br>              child: CustomPaint(<br>                painter: DrawingPainter(paths),<br>                child: Container(),<br>              ),<br>            ),<br>          ),<br>        ),<br>      ],<br>    );<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/344/1*2HPQE7MSmAkWphmBg7q4Gg.gif" /><figcaption>Drawing Painter</figcaption></figure><h4>Project 3: Progress Indicator Collection</h4><pre>/// A custom painter that draws a circular progress indicator.<br>///<br>/// This painter can be used to display progress in a circular shape.<br>/// It supports customization of colors, stroke width, and the progress value.<br>class CircularProgressPainter extends CustomPainter {<br>  /// The current progress value, ranging from 0.0 to 1.0.<br>  final double progress;<br><br>  /// The color of the background circle. Defaults to [Colors.grey].<br>  final Color backgroundColor;<br><br>  /// The color of the progress arc. Defaults to [Colors.blue].<br>  final Color progressColor;<br><br>  /// The width of the circle&#39;s stroke. Defaults to 8.0.<br>  final double strokeWidth;<br><br>  CircularProgressPainter({<br>    required this.progress,<br>    this.backgroundColor = Colors.grey,<br>    this.progressColor = Colors.blue,<br>    this.strokeWidth = 8.0,<br>  });<br><br>  @override<br>  void paint(Canvas canvas, Size size) {<br>    final center = Offset(size.width / 2, size.height / 2);<br>    final radius = (size.width - strokeWidth) / 2;<br><br>    // Background circle<br>    final backgroundPaint = Paint()<br>      ..color = backgroundColor.withOpacity(0.3)<br>      ..strokeWidth = strokeWidth<br>      ..style = PaintingStyle.stroke<br>      ..strokeCap = StrokeCap.round;<br><br>    canvas.drawCircle(center, radius, backgroundPaint);<br><br>    // Progress arc<br>    final progressPaint = Paint()<br>      ..color = progressColor<br>      ..strokeWidth = strokeWidth<br>      ..style = PaintingStyle.stroke<br>      ..strokeCap = StrokeCap.round;<br><br>    final sweepAngle = 2 * math.pi * progress;<br>    final rect = Rect.fromCircle(center: center, radius: radius);<br><br>    canvas.drawArc(<br>      rect,<br>      -math.pi / 2, // Start from top<br>      sweepAngle,<br>      false,<br>      progressPaint,<br>    );<br><br>    // Center text<br>    final textSpan = TextSpan(<br>      text: &#39;${(progress * 100).toInt()}%&#39;,<br>      style: TextStyle(<br>        color: Colors.black87,<br>        fontSize: 24,<br>        fontWeight: FontWeight.bold,<br>      ),<br>    );<br><br>    final textPainter = TextPainter(<br>      text: textSpan,<br>      textDirection: TextDirection.ltr,<br>      textAlign: TextAlign.center,<br>    );<br><br>    textPainter.layout();<br>    textPainter.paint(<br>      canvas,<br>      Offset(<br>        center.dx - textPainter.width / 2,<br>        center.dy - textPainter.height / 2,<br>      ),<br>    );<br>  }<br><br>  @override<br>  bool shouldRepaint(CustomPainter oldDelegate) {<br>    return oldDelegate is CircularProgressPainter &amp;&amp;<br>        oldDelegate.progress != progress;<br>  }<br>}<br><br><br><br>/// A custom painter that draws a linear progress indicator.<br>///<br>/// This painter can be used to display progress in a linear shape.<br>/// It supports customization of colors, height, and the progress value.<br>class LinearProgressPainter extends CustomPainter {<br>  /// The current progress value, ranging from 0.0 to 1.0.<br>  final double progress;<br><br>  /// The color of the background bar. Defaults to [Colors.grey].<br>  final Color backgroundColor;<br><br>  /// The color of the progress bar. Defaults to [Colors.blue].<br>  final Color progressColor;<br><br>  /// The height of the progress bar. Defaults to 8.0.<br>  final double height;<br><br><br><br>  LinearProgressPainter({<br>    required this.progress,<br>    this.backgroundColor = Colors.grey,<br>    this.progressColor = Colors.blue,<br>    this.height = 8.0,<br>  });<br><br>  @override<br>  void paint(Canvas canvas, Size size) {<br>    final backgroundRect = RRect.fromRectAndRadius(<br>      Rect.fromLTWH(0, (size.height - height) / 2, size.width, height),<br>      Radius.circular(height / 2),<br>    );<br><br>    final backgroundPaint = Paint()<br>      ..color = backgroundColor.withOpacity(0.3);<br><br>    canvas.drawRRect(backgroundRect, backgroundPaint);<br><br>    // Progress bar<br>    final progressWidth = size.width * progress;<br>    final progressRect = RRect.fromRectAndRadius(<br>      Rect.fromLTWH(0, (size.height - height) / 2, progressWidth, height),<br>      Radius.circular(height / 2),<br>    );<br><br>    final gradient = LinearGradient(<br>      colors: [<br>        progressColor.withOpacity(0.7),<br>        progressColor,<br>      ],<br>    );<br><br>    final progressPaint = Paint()<br>      ..shader = gradient.createShader(progressRect.outerRect);<br><br>    canvas.drawRRect(progressRect, progressPaint);<br>  }<br><br>  @override<br>  bool shouldRepaint(CustomPainter oldDelegate) {<br>    return oldDelegate is LinearProgressPainter &amp;&amp;<br>        oldDelegate.progress != progress;<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/346/1*jrhRlrrA1nQBeMs6hAHAlA.gif" /></figure><h4>Performance Tips</h4><p>Optimizing CustomPainter performance is crucial for smooth animations and responsive user interfaces. Here are essential techniques to ensure your custom graphics run at 60fps.</p><h4>1. Implement shouldRepaint Correctly</h4><p>The shouldRepaint method is your first line of defense against unnecessary redraws:</p><pre>class OptimizedPainter extends CustomPainter {<br>  final double animationValue;<br>  final Color color;<br>  final List&lt;Point&gt; points;<br>  <br>  OptimizedPainter({<br>    required this.animationValue,<br>    required this.color,<br>    required this.points,<br>  });<br><br>  @override<br>  void paint(Canvas canvas, Size size) {<br>    // Your painting logic here<br>  }<br><br>  @override<br>  bool shouldRepaint(CustomPainter oldDelegate) {<br>    if (oldDelegate is! OptimizedPainter) return true;<br>    <br>    return oldDelegate.animationValue != animationValue ||<br>           oldDelegate.color != color ||<br>           !listEquals(oldDelegate.points, points);<br>  }<br>}</pre><h4>2. Cache Expensive Operations</h4><p>Pre-calculate complex values and cache them when possible:</p><pre>class CachedPathPainter extends CustomPainter {<br>  final double progress;<br>  Path? _cachedPath;<br>  double? _lastSize;<br>  <br>  CachedPathPainter(this.progress);<br><br>  Path _createComplexPath(Size size) {<br>    final path = Path();<br>    <br>    // Expensive calculations here<br>    for (int i = 0; i &lt; 1000; i++) {<br>      final angle = (i / 1000) * 2 * math.pi;<br>      final radius = size.width * 0.3;<br>      final x = size.width / 2 + radius * math.cos(angle);<br>      final y = size.height / 2 + radius * math.sin(angle);<br>      <br>      if (i == 0) {<br>        path.moveTo(x, y);<br>      } else {<br>        path.lineTo(x, y);<br>      }<br>    }<br>    <br>    return path;<br>  }<br><br>  @override<br>  void paint(Canvas canvas, Size size) {<br>    // Cache the path only if size changed<br>    if (_cachedPath == null || _lastSize != size.width) {<br>      _cachedPath = _createComplexPath(size);<br>      _lastSize = size.width;<br>    }<br><br>    final paint = Paint()<br>      ..color = Colors.blue<br>      ..style = PaintingStyle.stroke<br>      ..strokeWidth = 2.0;<br><br>    // Use cached path with current progress<br>    final pathMetrics = _cachedPath!.computeMetrics();<br>    final pathMetric = pathMetrics.first;<br>    final extractedPath = pathMetric.extractPath(<br>      0.0,<br>      pathMetric.length * progress,<br>    );<br><br>    canvas.drawPath(extractedPath, paint);<br>  }<br><br>  @override<br>  bool shouldRepaint(CustomPainter oldDelegate) {<br>    return oldDelegate is CachedPathPainter &amp;&amp; <br>           oldDelegate.progress != progress;<br>  }<br>}</pre><h4>3. Use Efficient Drawing Methods</h4><p>Choose the most efficient drawing method for your use case:</p><pre>class EfficientDrawingPainter extends CustomPainter {<br>  final List&lt;Offset&gt; points;<br>  <br>  EfficientDrawingPainter(this.points);<br><br>  @override<br>  void paint(Canvas canvas, Size size) {<br>    final paint = Paint()<br>      ..color = Colors.blue<br>      ..strokeWidth = 4.0<br>      ..strokeCap = StrokeCap.round;<br><br>    // ❌ Inefficient: Drawing points individually<br>    // for (final point in points) {<br>    //   canvas.drawCircle(point, 2, paint);<br>    // }<br><br>    // ✅ Efficient: Draw all points at once<br>    canvas.drawPoints(PointMode.points, points, paint);<br><br>    // ✅ For connected lines, use drawPath instead of multiple drawLine calls<br>    if (points.length &gt; 1) {<br>      final path = Path();<br>      path.moveTo(points.first.dx, points.first.dy);<br>      <br>      for (int i = 1; i &lt; points.length; i++) {<br>        path.lineTo(points[i].dx, points[i].dy);<br>      }<br>      <br>      canvas.drawPath(path, paint);<br>    }<br>  }<br><br>  @override<br>  bool shouldRepaint(CustomPainter oldDelegate) {<br>    return oldDelegate is EfficientDrawingPainter &amp;&amp; <br>           !listEquals(oldDelegate.points, points);<br>  }<br>}</pre><h4>4. Minimize Paint Object Creation</h4><p>Reuse Paint objects when possible:</p><pre>class PaintOptimizedPainter extends CustomPainter {<br>  // ✅ Static paint objects for reuse<br>  static final _fillPaint = Paint()..style = PaintingStyle.fill;<br>  static final _strokePaint = Paint()<br>    ..style = PaintingStyle.stroke<br>    ..strokeWidth = 2.0;<br><br>  final List&lt;Circle&gt; circles;<br>  <br>  PaintOptimizedPainter(this.circles);<br><br>  @override<br>  void paint(Canvas canvas, Size size) {<br>    for (final circle in circles) {<br>      // ❌ Don&#39;t create new Paint objects in paint method<br>      // final paint = Paint()<br>      //   ..color = circle.color<br>      //   ..style = PaintingStyle.fill;<br>      <br>      // ✅ Reuse static paint objects<br>      _fillPaint.color = circle.color;<br>      canvas.drawCircle(circle.center, circle.radius, _fillPaint);<br>      <br>      _strokePaint.color = circle.borderColor;<br>      canvas.drawCircle(circle.center, circle.radius, _strokePaint);<br>    }<br>  }<br><br>  @override<br>  bool shouldRepaint(CustomPainter oldDelegate) {<br>    return oldDelegate is PaintOptimizedPainter &amp;&amp; <br>           !listEquals(oldDelegate.circles, circles);<br>  }<br>}<br><br>class Circle {<br>  final Offset center;<br>  final double radius;<br>  final Color color;<br>  final Color borderColor;<br>  <br>  Circle({<br>    required this.center,<br>    required this.radius,<br>    required this.color,<br>    required this.borderColor,<br>  });<br>}</pre><h4>5. Use Canvas Clipping Wisely</h4><p>Only draw what’s visible:</p><pre>class ClippedPainter extends CustomPainter {<br>  final List&lt;DrawableItem&gt; items;<br>  final Rect visibleArea;<br>  <br>  ClippedPainter(this.items, this.visibleArea);<br><br>  @override<br>  void paint(Canvas canvas, Size size) {<br>    // Clip to visible area only<br>    canvas.clipRect(visibleArea);<br><br>    final paint = Paint()..color = Colors.blue;<br><br>    for (final item in items) {<br>      // Only draw items that intersect with visible area<br>      if (item.bounds.overlaps(visibleArea)) {<br>        canvas.drawRect(item.bounds, paint);<br>      }<br>    }<br>  }<br><br>  @override<br>  bool shouldRepaint(CustomPainter oldDelegate) {<br>    return oldDelegate is ClippedPainter &amp;&amp; <br>           (!listEquals(oldDelegate.items, items) ||<br>            oldDelegate.visibleArea != visibleArea);<br>  }<br>}</pre><h4>6. Optimize Animation Performance</h4><p>Use appropriate animation techniques:</p><pre>class OptimizedAnimationPainter extends CustomPainter {<br>  final double animationValue;<br>  final AnimationController controller;<br>  <br>  OptimizedAnimationPainter(this.animationValue, this.controller);<br><br>  @override<br>  void paint(Canvas canvas, Size size) {<br>    final paint = Paint()<br>      ..color = Colors.blue<br>      ..style = PaintingStyle.fill;<br><br>    // Use easing functions for smooth animations<br>    final easedValue = Curves.easeInOut.transform(animationValue);<br>    <br>    final radius = size.width * 0.3 * easedValue;<br>    final center = Offset(size.width / 2, size.height / 2);<br>    <br>    canvas.drawCircle(center, radius, paint);<br>  }<br><br>  @override<br>  bool shouldRepaint(CustomPainter oldDelegate) {<br>    return oldDelegate is OptimizedAnimationPainter &amp;&amp; <br>           oldDelegate.animationValue != animationValue;<br>  }<br>}<br><br>// Usage with proper animation setup<br>class OptimizedAnimationWidget extends StatefulWidget {<br>  @override<br>  _OptimizedAnimationWidgetState createState() =&gt; <br>      _OptimizedAnimationWidgetState();<br>}<br><br>class _OptimizedAnimationWidgetState extends State&lt;OptimizedAnimationWidget&gt;<br>    with SingleTickerProviderStateMixin {<br>  late AnimationController _controller;<br><br>  @override<br>  void initState() {<br>    super.initState();<br>    _controller = AnimationController(<br>      duration: Duration(seconds: 2),<br>      vsync: this,<br>    )..repeat(reverse: true);<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return AnimatedBuilder(<br>      animation: _controller,<br>      builder: (context, child) {<br>        return CustomPaint(<br>          painter: OptimizedAnimationPainter(_controller.value, _controller),<br>          size: Size(200, 200),<br>        );<br>      },<br>    );<br>  }<br><br>  @override<br>  void dispose() {<br>    _controller.dispose();<br>    super.dispose();<br>  }<br>}</pre><h4>7. Profile and Debug Performance</h4><p>Use Flutter’s performance tools:</p><pre>class ProfiledPainter extends CustomPainter {<br>  final double animationValue;<br>  <br>  ProfiledPainter(this.animationValue);<br><br>  @override<br>  void paint(Canvas canvas, Size size) {<br>    // Use Timeline for profiling<br>    Timeline.startSync(&#39;CustomPainter.paint&#39;);<br>    <br>    try {<br>      // Your painting code here<br>      _drawComplexGraphics(canvas, size);<br>    } finally {<br>      Timeline.finishSync();<br>    }<br>  }<br><br>  void _drawComplexGraphics(Canvas canvas, Size size) {<br>    Timeline.startSync(&#39;ComplexGraphics&#39;);<br>    <br>    // Complex drawing operations<br>    final paint = Paint()..color = Colors.blue;<br>    <br>    for (int i = 0; i &lt; 1000; i++) {<br>      final angle = (i / 1000) * 2 * math.pi * animationValue;<br>      final x = size.width / 2 + 50 * math.cos(angle);<br>      final y = size.height / 2 + 50 * math.sin(angle);<br>      canvas.drawCircle(Offset(x, y), 2, paint);<br>    }<br>    <br>    Timeline.finishSync();<br>  }<br><br>  @override<br>  bool shouldRepaint(CustomPainter oldDelegate) {<br>    return oldDelegate is ProfiledPainter &amp;&amp; <br>           oldDelegate.animationValue != animationValue;<br>  }<br>}</pre><h4>Advanced Techniques</h4><p>Master these advanced CustomPainter techniques to create truly professional, production-ready graphics.</p><h4>1. Matrix Transformations</h4><p>Use matrix transformations for complex rotations, scaling, and skewing:</p><pre>class MatrixTransformPainter extends CustomPainter {<br>  final double rotation;<br>  final double scale;<br>  final Offset translation;<br><br>  MatrixTransformPainter({<br>    required this.rotation,<br>    required this.scale,<br>    required this.translation,<br>  });<br><br>  @override<br>  void paint(Canvas canvas, Size size) {<br>    final center = Offset(size.width / 2, size.height / 2);<br><br>    // Save the current canvas state<br>    canvas.save();<br><br>    // Method 1: Individual transformations<br>    canvas.translate(center.dx + translation.dx, center.dy + translation.dy);<br>    canvas.rotate(rotation);<br>    canvas.scale(scale);<br><br>    // Draw something at origin (will be transformed)<br>    final paint = Paint()<br>      ..color = Colors.blue<br>      ..style = PaintingStyle.fill;<br><br>    canvas.drawRect(Rect.fromCenter(center: Offset.zero, width: 100, height: 60), paint);<br><br>    // Restore canvas state<br>    canvas.restore();<br><br>    // Method 2: Using Matrix4 for complex transformations<br>    canvas.save();<br><br>    final matrix = Matrix4.identity()<br>      ..translate(center.dx, center.dy)<br>      ..rotateZ(rotation * 0.5)<br>      ..scale(scale * 0.8)<br>      ..translate(-center.dx, -center.dy);<br><br>    canvas.transform(matrix.storage);<br><br>    final paint2 = Paint()<br>      ..color = Colors.red.withValues(alpha: 0.7)<br>      ..style = PaintingStyle.fill;<br><br>    canvas.drawOval(Rect.fromCenter(center: center, width: 120, height: 80), paint2);<br><br>    canvas.restore();<br>  }<br><br>  @override<br>  bool shouldRepaint(CustomPainter oldDelegate) {<br>    return oldDelegate is MatrixTransformPainter &amp;&amp;<br>        (oldDelegate.rotation != rotation ||<br>            oldDelegate.scale != scale ||<br>            oldDelegate.translation != translation);<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*hUMi7uZGcMMWCybPTLDr8Q.gif" /><figcaption>Matrix Transform Painter</figcaption></figure><h4>2. Advanced Path Operations</h4><p>Combine, modify, and animate paths for complex shapes:</p><pre>class AdvancedPathPainter extends CustomPainter {<br>  final double morphProgress;<br><br>  AdvancedPathPainter(this.morphProgress);<br><br>  @override<br>  void paint(Canvas canvas, Size size) {<br>    final center = Offset(size.width / 2, size.height / 2);<br><br>    // Create two different paths<br>    final path1 = _createCirclePath(center, 80);<br>    final path2 = _createStarPath(center, 80);<br><br>    // Morph between paths (simplified approach)<br>    final morphedPath = _morphPaths(path1, path2, morphProgress);<br><br>    final paint = Paint()<br>      ..color = Colors.purple<br>      ..style = PaintingStyle.fill;<br><br>    canvas.drawPath(morphedPath, paint);<br><br>    // Path boolean operations<br>    _drawPathOperations(canvas, size);<br>  }<br><br>  Path _createCirclePath(Offset center, double radius) {<br>    return Path()..addOval(Rect.fromCircle(center: center, radius: radius));<br>  }<br><br>  Path _createStarPath(Offset center, double radius) {<br>    final path = Path();<br>    const points = 5;<br>    const innerRadius = 0.4;<br><br>    for (int i = 0; i &lt; points * 2; i++) {<br>      final angle = (i * math.pi) / points;<br>      final r = i.isEven ? radius : radius * innerRadius;<br>      final x = center.dx + r * math.cos(angle - math.pi / 2);<br>      final y = center.dy + r * math.sin(angle - math.pi / 2);<br><br>      if (i == 0) {<br>        path.moveTo(x, y);<br>      } else {<br>        path.lineTo(x, y);<br>      }<br>    }<br><br>    path.close();<br>    return path;<br>  }<br><br>  Path _morphPaths(Path path1, Path path2, double t) {<br>    // Simplified morphing - in production, use proper path interpolation<br>    final morphedPath = Path();<br><br>    // This is a simplified example - real morphing requires extracting<br>    // path metrics and interpolating between corresponding points<br>    if (t &lt; 0.5) {<br>      return path1;<br>    } else {<br>      return path2;<br>    }<br>  }<br><br>  void _drawPathOperations(Canvas canvas, Size size) {<br>    final rect1 = Rect.fromLTWH(50, size.height - 150, 100, 80);<br>    final rect2 = Rect.fromLTWH(100, size.height - 130, 100, 80);<br><br>    final path1 = Path()..addRect(rect1);<br>    final path2 = Path()..addRect(rect2);<br><br>    // Path operations<br>    final unionPath = Path.combine(PathOperation.union, path1, path2);<br>    final intersectPath = Path.combine(PathOperation.intersect, path1, path2);<br>    final differencePath = Path.combine(PathOperation.difference, path1, path2);<br><br>    final unionPaint = Paint()<br>      ..color = Colors.blue.withOpacity(0.7)<br>      ..style = PaintingStyle.fill;<br><br>    final intersectPaint = Paint()<br>      ..color = Colors.red.withOpacity(0.7)<br>      ..style = PaintingStyle.fill;<br><br>    final differencePaint = Paint()<br>      ..color = Colors.green.withOpacity(0.7)<br>      ..style = PaintingStyle.fill;<br>  }<br><br>  @override<br>  bool shouldRepaint(CustomPainter oldDelegate) {<br>    return oldDelegate is AdvancedPathPainter &amp;&amp;<br>        oldDelegate.morphProgress != morphProgress;<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/340/1*DVJINattSw8oPajhxysxng.gif" /><figcaption>Advanced Path Painter</figcaption></figure><h4>3. Custom Shader Effects</h4><p>Create stunning visual effects with shaders:</p><pre>class ShaderEffectsPainter extends CustomPainter {<br>  final double time;<br><br>  ShaderEffectsPainter(this.time);<br><br>  @override<br>  void paint(Canvas canvas, Size size) {<br>    // Noise effect using multiple gradients<br>    _drawNoiseEffect(canvas, size);<br><br>    // Ripple effect<br>    _drawRippleEffect(canvas, size);<br><br>    // Plasma effect<br>    _drawPlasmaEffect(canvas, size);<br>  }<br><br>  void _drawNoiseEffect(Canvas canvas, Size size) {<br>    for (int i = 0; i &lt; 50; i++) {<br>      final random = math.Random(i);<br>      final x = random.nextDouble() * size.width;<br>      final y = random.nextDouble() * size.height;<br><br>      final gradient = RadialGradient(<br>        colors: [<br>          Colors.white.withValues(alpha: 0.1 + 0.1 * math.sin(time + i)),<br>          Colors.transparent,<br>        ],<br>      );<br><br>      final rect = Rect.fromCircle(center: Offset(x, y), radius: 20);<br>      final paint = Paint()<br>        ..shader = gradient.createShader(rect);<br><br>      canvas.drawCircle(Offset(x, y), 20, paint);<br>    }<br>  }<br><br>  void _drawRippleEffect(Canvas canvas, Size size) {<br>    final center = Offset(size.width * 0.3, size.height * 0.7);<br><br>    for (int i = 0; i &lt; 5; i++) {<br>      final rippleTime = time - i * 0.3;<br>      if (rippleTime &lt; 0) continue;<br><br>      final radius = (rippleTime % 2.0) * 100;<br>      final opacity = 1.0 - (rippleTime % 2.0) / 2.0;<br><br>      final paint = Paint()<br>        ..color = Colors.cyan.withValues(alpha: opacity * 0.5)<br>        ..strokeWidth = 3.0<br>        ..style = PaintingStyle.stroke;<br><br>      canvas.drawCircle(center, radius, paint);<br>    }<br>  }<br><br>  void _drawPlasmaEffect(Canvas canvas, Size size) {<br>    const int steps = 50;<br>    final paint = Paint()..style = PaintingStyle.fill;<br><br>    for (int x = 0; x &lt; steps; x++) {<br>      for (int y = 0; y &lt; steps; y++) {<br>        final nx = x / steps;<br>        final ny = y / steps;<br><br>        // Plasma calculation<br>        final plasma = math.sin(nx * 10 + time) +<br>            math.sin(ny * 10 + time) +<br>            math.sin((nx + ny) * 10 + time) +<br>            math.sin(math.sqrt(nx * nx + ny * ny) * 10 + time);<br><br>        final normalizedPlasma = (plasma + 4) / 8; // Normalize to 0-1<br><br>        paint.color = HSVColor.fromAHSV(<br>          0.1,<br>          normalizedPlasma * 360,<br>          1.0,<br>          normalizedPlasma,<br>        ).toColor();<br><br>        final rect = Rect.fromLTWH(<br>          size.width * 0.6 + (x / steps) * 100,<br>          size.height * 0.1 + (y / steps) * 100,<br>          100 / steps,<br>          100 / steps,<br>        );<br><br>        canvas.drawRect(rect, paint);<br>      }<br>    }<br>  }<br><br>  @override<br>  bool shouldRepaint(CustomPainter oldDelegate) {<br>    return oldDelegate is ShaderEffectsPainter &amp;&amp; oldDelegate.time != time;<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/358/1*WvXNT8k-WveElAEmYYcJ3w.gif" /><figcaption>Shader Effects Painter</figcaption></figure><h4>4. Particle Systems</h4><p>Create dynamic particle effects:</p><pre>class Particle {<br>  Offset position;<br>  Offset velocity;<br>  double life;<br>  double maxLife;<br>  Color color;<br>  double size;<br><br>  Particle({<br>    required this.position,<br>    required this.velocity,<br>    required this.life,<br>    required this.maxLife,<br>    required this.color,<br>    required this.size,<br>  });<br><br>  void update(double deltaTime) {<br>    position += velocity * deltaTime;<br>    life -= deltaTime;<br>    velocity = velocity * 0.995; // Friction<br>  }<br><br>  bool get isDead =&gt; life &lt;= 0;<br><br>  double get opacity =&gt; (life / maxLife).clamp(0.0, 1.0);<br>}<br><br>class ParticleSystemPainter extends CustomPainter {<br>  final List&lt;Particle&gt; particles;<br>  final Offset emitterPosition;<br><br>  ParticleSystemPainter({<br>    required this.particles,<br>    required this.emitterPosition,<br>  });<br><br>  @override<br>  void paint(Canvas canvas, Size size) {<br>    final paint = Paint()<br>      ..style = PaintingStyle.fill<br>      ..isAntiAlias = true;<br><br>    for (final particle in particles) {<br>      if (particle.isDead) continue;<br><br>      paint.color = particle.color.withValues(alpha :particle.opacity);<br><br>      // Draw particle with glow effect<br>      final glowPaint = Paint()<br>        ..color = particle.color.withValues(alpha: particle.opacity * 0.3)<br>        ..maskFilter = MaskFilter.blur(BlurStyle.normal, particle.size * 0.5);<br><br>      canvas.drawCircle(particle.position, particle.size * 1.5, glowPaint);<br>      canvas.drawCircle(particle.position, particle.size, paint);<br>    }<br>  }<br><br>  @override<br>  bool shouldRepaint(CustomPainter oldDelegate) {<br>    return true; // Always repaint for particles<br>  }<br>}<br><br>class ParticleSystemWidget extends StatefulWidget {<br>  const ParticleSystemWidget({super.key});<br><br>  @override<br>  State&lt;ParticleSystemWidget&gt; createState() =&gt; _ParticleSystemWidgetState();<br>}<br><br>class _ParticleSystemWidgetState extends State&lt;ParticleSystemWidget&gt;<br>    with SingleTickerProviderStateMixin {<br>  late AnimationController _controller;<br>  List&lt;Particle&gt; particles = [];<br>  DateTime? lastTime;<br>  final math.Random random = math.Random();<br>  Offset emitterPosition = Offset(200, 200);<br><br>  @override<br>  void initState() {<br>    super.initState();<br>    _controller = AnimationController(<br>      duration: Duration(seconds: 1),<br>      vsync: this,<br>    )..addListener(_updateParticles);<br><br>    _controller.repeat();<br>  }<br><br>  void _updateParticles() {<br>    final now = DateTime.now();<br>    final deltaTime = lastTime != null<br>        ? now.difference(lastTime!).inMilliseconds / 1000.0<br>        : 0.016; // 60fps fallback<br>    lastTime = now;<br><br>    // Update existing particles<br>    particles = particles.where((particle) {<br>      particle.update(deltaTime);<br>      return !particle.isDead;<br>    }).toList();<br><br>    // Emit new particles<br>    if (particles.length &lt; 100) {<br>      for (int i = 0; i &lt; 3; i++) {<br>        _emitParticle();<br>      }<br>    }<br><br>    setState(() {});<br>  }<br><br>  void _emitParticle() {<br>    final angle = random.nextDouble() * 2 * math.pi;<br>    final speed = 50 + random.nextDouble() * 100;<br><br>    particles.add(Particle(<br>      position: emitterPosition,<br>      velocity: Offset(<br>        math.cos(angle) * speed,<br>        math.sin(angle) * speed - 30, // Slight upward bias<br>      ),<br>      life: 2 + random.nextDouble() * 3,<br>      maxLife: 5,<br>      color: HSVColor.fromAHSV(<br>        1.0,<br>        random.nextDouble() * 60 + 20, // Orange to yellow<br>        0.8 + random.nextDouble() * 0.2,<br>        0.8 + random.nextDouble() * 0.2,<br>      ).toColor(),<br>      size: 2 + random.nextDouble() * 4,<br>    ));<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return GestureDetector(<br>      onPanUpdate: (details) {<br>        setState(() {<br>          emitterPosition = details.localPosition;<br>        });<br>      },<br>      child: CustomPaint(<br>        painter: ParticleSystemPainter(<br>          particles: particles,<br>          emitterPosition: emitterPosition,<br>        ),<br>        size: Size.infinite,<br>      ),<br>    );<br>  }<br><br>  @override<br>  void dispose() {<br>    _controller.dispose();<br>    super.dispose();<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/1*RYKHRlN-bsO8FI44RGv46A.gif" /><figcaption>Particle System Painter</figcaption></figure><h4>5. Interactive Hit Testing</h4><p>Implement precise touch detection for custom shapes:</p><pre>class InteractiveShape {<br>  final Path path;<br>  final Color color;<br>  final String id;<br>  bool isSelected;<br><br>  InteractiveShape({<br>    required this.path,<br>    required this.color,<br>    required this.id,<br>    this.isSelected = false,<br>  });<br>}<br><br>class InteractivePainter extends CustomPainter {<br>  final List&lt;InteractiveShape&gt; shapes;<br>  final Offset? touchPosition;<br><br>  InteractivePainter({<br>    required this.shapes,<br>    this.touchPosition,<br>  });<br><br>  @override<br>  void paint(Canvas canvas, Size size) {<br>    for (final shape in shapes) {<br>      final paint = Paint()<br>        ..color = shape.isSelected<br>            ? shape.color.withValues(alpha: 0.8)<br>            : shape.color.withValues(alpha: 0.6)<br>        ..style = PaintingStyle.fill;<br><br>      canvas.drawPath(shape.path, paint);<br><br>      // Draw selection outline<br>      if (shape.isSelected) {<br>        final outlinePaint = Paint()<br>          ..color = Colors.white<br>          ..strokeWidth = 3.0<br>          ..style = PaintingStyle.stroke;<br><br>        canvas.drawPath(shape.path, outlinePaint);<br>      }<br>    }<br><br>    // Draw touch indicator<br>    if (touchPosition != null) {<br>      final touchPaint = Paint()<br>        ..color = Colors.red.withValues(alpha: 0.5)<br>        ..style = PaintingStyle.fill;<br><br>      canvas.drawCircle(touchPosition!, 10, touchPaint);<br>    }<br>  }<br><br>  InteractiveShape? hitTestShape(Offset position) {<br>    // Test shapes in reverse order (top to bottom)<br>    for (int i = shapes.length - 1; i &gt;= 0; i--) {<br>      if (shapes[i].path.contains(position)) {<br>        return shapes[i];<br>      }<br>    }<br>    return null;<br>  }<br><br>  @override<br>  bool shouldRepaint(CustomPainter oldDelegate) {<br>    return oldDelegate is InteractivePainter &amp;&amp;<br>        (oldDelegate.touchPosition != touchPosition ||<br>            !listEquals(oldDelegate.shapes, shapes));<br>  }<br><br>  @override<br>  bool? hitTest(Offset position) =&gt; true; // Enable hit testing<br>}<br><br>class InteractiveCanvas extends StatefulWidget {<br>  const InteractiveCanvas({super.key});<br><br>  @override<br>  State&lt;InteractiveCanvas&gt; createState() =&gt; _InteractiveCanvasState();<br>}<br><br>class _InteractiveCanvasState extends State&lt;InteractiveCanvas&gt; {<br>  List&lt;InteractiveShape&gt; shapes = [];<br>  Offset? currentTouchPosition;<br>  InteractivePainter? painter;<br><br>  @override<br>  void initState() {<br>    super.initState();<br>    _initializeShapes();<br>  }<br><br>  void _initializeShapes() {<br>    // Create some sample shapes<br>    final rect1 = Path()..addRect(Rect.fromLTWH(50, 50, 100, 80));<br>    final circle1 = Path()..addOval(Rect.fromLTWH(200, 50, 80, 80));<br>    final triangle = Path()<br>      ..moveTo(350, 50)<br>      ..lineTo(400, 130)<br>      ..lineTo(300, 130)<br>      ..close();<br><br>    shapes = [<br>      InteractiveShape(path: rect1, color: Colors.blue, id: &#39;rect1&#39;),<br>      InteractiveShape(path: circle1, color: Colors.green, id: &#39;circle1&#39;),<br>      InteractiveShape(path: triangle, color: Colors.red, id: &#39;triangle&#39;),<br>    ];<br>  }<br><br>  void _handleTap(Offset position) {<br>    setState(() {<br>      currentTouchPosition = position;<br><br>      // Clear all selections first<br>      for (final shape in shapes) {<br>        shape.isSelected = false;<br>      }<br><br>      // Find and select the tapped shape<br>      final hitShape = painter?.hitTestShape(position);<br>      if (hitShape != null) {<br>        hitShape.isSelected = true;<br>      }<br>    });<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    painter = InteractivePainter(<br>      shapes: shapes,<br>      touchPosition: currentTouchPosition,<br>    );<br><br>    return GestureDetector(<br>      onTapDown: (details) =&gt; _handleTap(details.localPosition),<br>      child: CustomPaint(<br>        painter: painter,<br>        size: Size.infinite,<br>      ),<br>    );<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*oOV2A74_knzaBYu3MZLakw.gif" /><figcaption>Interactive Painter</figcaption></figure><h4>6. Advanced Animation Techniques</h4><p>Create complex, layered animations:</p><pre>class LayeredAnimationPainter extends CustomPainter {<br>  final double primaryAnimation;<br>  final double secondaryAnimation;<br>  final double tertiaryAnimation;<br><br>  LayeredAnimationPainter({<br>    required this.primaryAnimation,<br>    required this.secondaryAnimation,<br>    required this.tertiaryAnimation,<br>  });<br><br>  @override<br>  void paint(Canvas canvas, Size size) {<br>    final center = Offset(size.width / 2, size.height / 2);<br><br>    // Layer 1: Rotating background rings<br>    _drawRotatingRings(canvas, center, primaryAnimation);<br><br>    // Layer 2: Pulsing center circle<br>    _drawPulsingCenter(canvas, center, secondaryAnimation);<br><br>    // Layer 3: Orbiting satellites<br>    _drawOrbitingSatellites(canvas, center, tertiaryAnimation);<br><br>    // Layer 4: Floating particles<br>    _drawFloatingParticles(canvas, size, primaryAnimation);<br>  }<br><br>  void _drawRotatingRings(Canvas canvas, Offset center, double animation) {<br>    final paint = Paint()<br>      ..style = PaintingStyle.stroke<br>      ..strokeWidth = 2.0;<br><br>    for (int i = 0; i &lt; 3; i++) {<br>      final radius = 80.0 + (i * 30);<br>      final rotation = animation * 2 * math.pi + (i * math.pi / 3);<br><br>      canvas.save();<br>      canvas.translate(center.dx, center.dy);<br>      canvas.rotate(rotation);<br><br>      paint.color = HSVColor.fromAHSV(<br>        0.7,<br>        (i * 120.0) % 360,<br>        0.8,<br>        0.9,<br>      ).toColor();<br><br>      // Draw segmented ring<br>      for (int j = 0; j &lt; 8; j++) {<br>        final startAngle = (j * math.pi / 4);<br>        final sweepAngle = math.pi / 6;<br><br>        canvas.drawArc(<br>          Rect.fromCircle(center: Offset.zero, radius: radius),<br>          startAngle,<br>          sweepAngle,<br>          false,<br>          paint,<br>        );<br>      }<br><br>      canvas.restore();<br>    }<br>  }<br><br>  void _drawPulsingCenter(Canvas canvas, Offset center, double animation) {<br>    final pulse = 0.8 + 0.2 * math.sin(animation * 4 * math.pi);<br>    final radius = 40 * pulse;<br><br>    final gradient = RadialGradient(<br>      colors: [<br>        Colors.white,<br>        Colors.blue.withValues(alpha: 0.8),<br>        Colors.transparent,<br>      ],<br>      stops: [0.0, 0.7, 1.0],<br>    );<br><br>    final paint = Paint()<br>      ..shader = gradient.createShader(<br>          Rect.fromCircle(center: center, radius: radius)<br>      );<br><br>    canvas.drawCircle(center, radius, paint);<br>  }<br><br>  void _drawOrbitingSatellites(Canvas canvas, Offset center, double animation) {<br>    final paint = Paint()<br>      ..style = PaintingStyle.fill;<br><br>    for (int i = 0; i &lt; 4; i++) {<br>      final orbitRadius = 120.0 + (i * 20);<br>      final angle = animation * 2 * math.pi + (i * math.pi / 2);<br>      final satelliteSize = 8.0 + (i * 2);<br><br>      final x = center.dx + orbitRadius * math.cos(angle);<br>      final y = center.dy + orbitRadius * math.sin(angle);<br><br>      paint.color = HSVColor.fromAHSV(<br>        1.0,<br>        (animation * 360 + i * 90) % 360,<br>        0.9,<br>        0.9,<br>      ).toColor();<br><br>      // Draw satellite with trail<br>      final trailPaint = Paint()<br>        ..color = paint.color.withValues(alpha: 0.3)<br>        ..style = PaintingStyle.stroke<br>        ..strokeWidth = 2.0;<br><br>      // Trail path<br>      final trailPath = Path();<br>      for (int j = 1; j &lt;= 10; j++) {<br>        final trailAngle = angle - (j * 0.1);<br>        final trailX = center.dx + orbitRadius * math.cos(trailAngle);<br>        final trailY = center.dy + orbitRadius * math.sin(trailAngle);<br><br>        if (j == 1) {<br>          trailPath.moveTo(trailX, trailY);<br>        } else {<br>          trailPath.lineTo(trailX, trailY);<br>        }<br>      }<br><br>      trailPaint.color = paint.color.withValues(alpha: 0.3 / 10);<br>      canvas.drawPath(trailPath, trailPaint);<br><br>      // Draw satellite<br>      canvas.drawCircle(Offset(x, y), satelliteSize, paint);<br>    }<br>  }<br><br>  void _drawFloatingParticles(Canvas canvas, Size size, double animation) {<br>    final paint = Paint()<br>      ..style = PaintingStyle.fill;<br><br>    final random = math.Random(42); // Fixed seed for consistent particles<br><br>    for (int i = 0; i &lt; 30; i++) {<br>      final baseX = random.nextDouble() * size.width;<br>      final baseY = random.nextDouble() * size.height;<br><br>      final floatOffset = 20 * math.sin(animation * 2 * math.pi + i);<br>      final x = baseX + floatOffset;<br>      final y = baseY + floatOffset * 0.5;<br><br>      final particleSize = 2 + random.nextDouble() * 3;<br>      final opacity = 0.3 + 0.4 * math.sin(animation * math.pi + i);<br><br>      paint.color = Colors.white.withValues(alpha: opacity);<br>      canvas.drawCircle(Offset(x, y), particleSize, paint);<br>    }<br>  }<br><br>  @override<br>  bool shouldRepaint(CustomPainter oldDelegate) {<br>    return oldDelegate is LayeredAnimationPainter &amp;&amp;<br>        (oldDelegate.primaryAnimation != primaryAnimation ||<br>            oldDelegate.secondaryAnimation != secondaryAnimation ||<br>            oldDelegate.tertiaryAnimation != tertiaryAnimation);<br>  }<br>}<br><br>class LayeredAnimationWidget extends StatefulWidget {<br>  const LayeredAnimationWidget({super.key});<br><br>  @override<br>  State&lt;LayeredAnimationWidget&gt; createState() =&gt; _LayeredAnimationWidgetState();<br>}<br><br>class _LayeredAnimationWidgetState extends State&lt;LayeredAnimationWidget&gt;<br>    with TickerProviderStateMixin {<br>  late AnimationController _primaryController;<br>  late AnimationController _secondaryController;<br>  late AnimationController _tertiaryController;<br><br>  @override<br>  void initState() {<br>    super.initState();<br><br>    _primaryController = AnimationController(<br>      duration: Duration(seconds: 8),<br>      vsync: this,<br>    )..repeat();<br><br>    _secondaryController = AnimationController(<br>      duration: Duration(seconds: 3),<br>      vsync: this,<br>    )..repeat();<br><br>    _tertiaryController = AnimationController(<br>      duration: Duration(seconds: 5),<br>      vsync: this,<br>    )..repeat();<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return AnimatedBuilder(<br>      animation: Listenable.merge([<br>        _primaryController,<br>        _secondaryController,<br>        _tertiaryController,<br>      ]),<br>      builder: (context, child) {<br>        return CustomPaint(<br>          painter: LayeredAnimationPainter(<br>            primaryAnimation: _primaryController.value,<br>            secondaryAnimation: _secondaryController.value,<br>            tertiaryAnimation: _tertiaryController.value,<br>          ),<br>          size: Size(400, 400),<br>        );<br>      },<br>    );<br>  }<br><br>  @override<br>  void dispose() {<br>    _primaryController.dispose();<br>    _secondaryController.dispose();<br>    _tertiaryController.dispose();<br>    super.dispose();<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/1*MGNT_kYhkCuTfk7pnIQrHQ.gif" /><figcaption>Layered Animation Painter</figcaption></figure><h4>Conclusion</h4><p>Congratulations! You’ve now mastered the complete spectrum of Flutter CustomPainter capabilities. From basic shapes to complex particle systems, from simple animations to advanced shader effects, you now have the tools to create truly stunning, professional-grade custom graphics in your Flutter applications.</p><h4>Key Takeaways</h4><p>✅ <strong>Master the fundamentals</strong>: Canvas, Paint, and Size are your building blocks<br> ✅ <strong>Optimize for performance</strong>: Always implement shouldRepaint correctly and cache expensive operations<br> ✅ <strong>Think in layers</strong>: Complex visuals are built from simple, layered components<br> ✅ <strong>Profile and measure</strong>: Use Flutter&#39;s performance tools to ensure smooth 60fps animations<br> ✅ <strong>Practice regularly</strong>: The best way to master CustomPainter is through hands-on experimentation</p><h4>Next Steps</h4><ul><li><strong>Experiment with the examples</strong>: Modify the code samples to create your own variations</li><li><strong>Build real projects</strong>: Apply these techniques to solve actual UI challenges in your apps</li><li><strong>Study performance</strong>: Use Flutter Inspector and Timeline to optimize your custom painters</li><li><strong>Share your creations</strong>: The Flutter community loves seeing creative CustomPainter implementations</li><li><strong>Stay updated</strong>: Flutter’s canvas capabilities continue to evolve with new features and optimizations</li></ul><h4>Resources for Continued Learning</h4><ul><li><strong>Flutter Documentation</strong>: <a href="https://flutter.dev/docs">flutter.dev/docs</a></li><li><strong>Dart Canvas API</strong>: Deep dive into the Canvas class methods</li><li><strong>Flutter Community</strong>: Join discussions about custom graphics and animations</li><li><strong>Performance Profiling</strong>: Master Flutter’s debugging and profiling tools</li></ul><p>Remember, CustomPainter is not just about drawing shapes — it’s about crafting experiences that delight users and set your app apart from the competition. With these advanced techniques in your toolkit, you’re ready to push the boundaries of what’s possible in Flutter UI development.</p><p>Happy painting! 🎨</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f9b1e8575e6c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Supercharge Your Laravel SEO with IndexNow: Real-Time Search Engine Notifications]]></title>
            <link>https://banatube.medium.com/supercharge-your-laravel-seo-with-indexnow-real-time-search-engine-notifications-f30726773657?source=rss-73f4bbebcd9d------2</link>
            <guid isPermaLink="false">https://medium.com/p/f30726773657</guid>
            <category><![CDATA[seo]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[indexnow]]></category>
            <category><![CDATA[searchengineoptimization]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Banatube]]></dc:creator>
            <pubDate>Tue, 13 May 2025 18:48:00 GMT</pubDate>
            <atom:updated>2025-05-13T18:48:00.361Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0rkhtxOIsf8F03WW88SOhg.png" /></figure><p>Search engine optimization (SEO) is a crucial aspect of any web application. One of the most frustrating SEO challenges is waiting for search engines to discover and index your content changes. What if you could notify search engines instantly when your content changes? Enter <strong>Laravel IndexNow</strong> — a powerful package that brings this capability directly to your Laravel applications.</p><h4>What is IndexNow and Why Should You Care?</h4><p><a href="https://www.indexnow.org/">IndexNow</a> is an open protocol developed to help websites notify search engines immediately when content is created, updated, or deleted. Instead of waiting for search engines to crawl your site (which can take days or weeks), IndexNow lets you proactively inform them about changes, leading to faster indexing and more up-to-date search results.</p><p>Major search engines including Microsoft Bing, Yandex, and others have adopted this protocol, with Google showing interest in the technology as well. By implementing IndexNow, you can ensure your content gets indexed faster across multiple search engines with a single API call.</p><h4>Introducing Laravel IndexNow</h4><p><a href="https://github.com/ymigval/laravel-indexnow">Laravel IndexNow</a> is a package created by ymigval that simplifies the integration of the IndexNow protocol with your Laravel applications. This elegant solution provides a clean, Laravel-style approach to notifying search engines about URL changes in real-time.</p><h4>Key Features</h4><ul><li><strong>Instant Search Engine Notification</strong>: Alert search engines as soon as content changes</li><li><strong>Simple Laravel Integration</strong>: Uses Laravel’s familiar package structure and conventions</li><li><strong>Single and Bulk URL Submissions</strong>: Submit one URL or multiple URLs in a batch</li><li><strong>Built-in Spam Prevention</strong>: Protection mechanisms to prevent abuse</li><li><strong>Detailed Logging System</strong>: Track all submissions and responses</li><li><strong>Highly Configurable</strong>: Customize according to your specific needs</li></ul><h3>Getting Started with Laravel IndexNow</h3><h4>Installation</h4><p>Adding this package to your Laravel project is simple. Just run:</p><pre>composer require ymigval/laravel-indexnow</pre><h4>Configuration</h4><ol><li>First, publish the configuration file:</li></ol><pre>php artisan vendor:publish --tag=&quot;indexnow&quot;</pre><p>2. Generate an IndexNow API key from one of these services:</p><ul><li><a href="https://www.bing.com/indexnow/getstarted#implementation">Microsoft Bing</a></li><li><a href="https://www.nowindex.org/indexnow-key/">NowIndex</a></li></ul><p>3. Add your API key to your .env file:</p><pre>INDEXNOW_API_KEY=your_api_key_here</pre><h4>Key File Verification</h4><p>For the IndexNow protocol to work, search engines need to verify that you own the domain. This is done by placing a text file with your API key at your domain’s root. <strong>The good news is that this key file is automatically generated and managed by the Laravel IndexNow package</strong>, so you don’t have to manually create it:</p><pre>https://www.example.com/4cea016a4ddb408592569456a9c4896b.txt</pre><p>The package includes helpful commands to manage and verify this setup:</p><pre># View your IndexNow API key<br>php artisan indexnow:apikey<br><br># Check IndexNow package status and configuration<br>php artisan indexnow:status</pre><p>The indexnow:status command is particularly useful as it performs a thorough check of your configuration, verifying:</p><ul><li>API Key configuration and validity</li><li>Key file accessibility</li><li>Search engine settings</li><li>Submissions status</li><li>Route registration</li><li>Overall package health and recommendations</li></ul><h4>Practical Usage Examples</h4><p><strong>Submitting a Single URL</strong></p><pre>use Ymigval\LaravelIndexnow\Facade\IndexNow;<br><br>// Notify search engines about a new or updated page<br>IndexNow::submit(&#39;https://www.example.com/my-page&#39;);</pre><p><strong>Submitting Multiple URLs</strong></p><pre>use Ymigval\LaravelIndexnow\Facade\IndexNow;<br><br>// Using an array<br>IndexNow::submit([<br>    &#39;https://www.example.com/page-1&#39;,<br>    &#39;https://www.example.com/page-2&#39;,<br>    &#39;https://www.example.com/page-3&#39;,<br>]);<br><br>// Or using method chaining for more readability<br>IndexNow::setUrl(&#39;https://www.example.com/page-1&#39;)<br>        -&gt;setUrl(&#39;https://www.example.com/page-2&#39;)<br>        -&gt;setUrl(&#39;https://www.example.com/page-3&#39;)<br>        -&gt;submit();</pre><h4>Integrating with Your Workflow</h4><p>The real power of this package comes from integrating it into your existing content management workflow. Here are some common integration points:</p><h4>Model Observers</h4><p>You can automatically notify search engines when your models are updated:</p><pre>&lt;?php<br><br>namespace App\Observers;<br><br>use App\Models\Article;<br>use Ymigval\LaravelIndexnow\Facade\IndexNow;<br><br>class ArticleObserver<br>{<br>    /**<br>     * Handle the Article &quot;created&quot; event.<br>     */<br>    public function created(Article $article)<br>    {<br>        IndexNow::submit(url(https://medium.com/&quot;/articles/%7B$article-&gt;slug%7D&quot;));<br>    }<br><br>    /**<br>     * Handle the Article &quot;updated&quot; event.<br>     */<br>    public function updated(Article $article)<br>    {<br>        IndexNow::submit(url(https://medium.com/&quot;/articles/%7B$article-&gt;slug%7D&quot;));<br>    }<br><br>    /**<br>     * Handle the Article &quot;deleted&quot; event.<br>     */<br>    public function deleted(Article $article)<br>    {<br>        IndexNow::submit(url(https://medium.com/&quot;/articles/%7B$article-&gt;slug%7D&quot;));<br>    }<br>}</pre><h4>Queued Jobs</h4><p>For better performance, you might want to process IndexNow submissions in the background:</p><pre>&lt;?php<br><br>namespace App\Jobs;<br><br>use Illuminate\Bus\Queueable;<br>use Illuminate\Contracts\Queue\ShouldQueue;<br>use Illuminate\Foundation\Bus\Dispatchable;<br>use Illuminate\Queue\InteractsWithQueue;<br>use Illuminate\Queue\SerializesModels;<br>use Ymigval\LaravelIndexnow\Facade\IndexNow;<br><br>class SubmitUrlToIndexNow implements ShouldQueue<br>{<br>    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;<br><br>    protected $url;<br><br>    public function __construct($url)<br>    {<br>        $this-&gt;url = $url;<br>    }<br><br>    public function handle()<br>    {<br>        IndexNow::submit($this-&gt;url);<br>    }<br>}</pre><p>Then dispatch the job whenever content changes:</p><pre>SubmitUrlToIndexNow::dispatch(&#39;https://www.example.com/my-page&#39;);</pre><h4>Monitoring and Maintenance</h4><p>The package includes a logging system that tracks all submissions and their responses. You can view these logs using:</p><pre>php artisan indexnow:logs</pre><p>This command displays a table with information about recent submissions, including status codes and any error messages.</p><h4>Security and Spam Prevention</h4><p>Laravel IndexNow includes built-in spam protection that temporarily blocks requests for 24 hours when suspicious activity is detected. This helps ensure your implementation adheres to the IndexNow protocol’s guidelines and prevents potential abuse.</p><h4>Performance Considerations</h4><p>While the package is designed to be lightweight, it’s worth noting a few performance considerations:</p><ol><li><strong>API Rate Limits</strong>: Most search engines impose rate limits on IndexNow submissions</li><li><strong>Queue Processing</strong>: Consider using Laravel’s queue system for high-traffic sites</li><li><strong>Selective Notification</strong>: Only notify search engines about important content changes</li></ol><h4>Conclusion</h4><p>The Laravel IndexNow package bridges an important gap in the SEO workflow by enabling real-time search engine notifications. By implementing this package, you can significantly reduce the time it takes for your content to appear in search results, potentially improving your overall SEO performance.</p><p>With its simple integration, robust features, and Laravel-native approach, this package is a must-have for any Laravel developer looking to optimize their application’s search engine visibility.</p><p>For more information, visit the <a href="https://github.com/ymigval/laravel-indexnow">GitHub repository</a>.</p><p><em>Are you using IndexNow in your Laravel applications? Share your experiences in the comments below!</em></p><h3>Submitting a Single URL</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f30726773657" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Laravel Model Cache: Supercharge Your Eloquent Queries with Zero Effort]]></title>
            <link>https://banatube.medium.com/laravel-model-cache-supercharge-your-eloquent-queries-with-zero-effort-048d9e7bbb3e?source=rss-73f4bbebcd9d------2</link>
            <guid isPermaLink="false">https://medium.com/p/048d9e7bbb3e</guid>
            <category><![CDATA[caching]]></category>
            <category><![CDATA[web-performance]]></category>
            <category><![CDATA[database-optimization]]></category>
            <category><![CDATA[php-development]]></category>
            <category><![CDATA[laravel]]></category>
            <dc:creator><![CDATA[Banatube]]></dc:creator>
            <pubDate>Thu, 01 May 2025 15:49:45 GMT</pubDate>
            <atom:updated>2025-05-21T18:37:44.014Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*TNTxOMZcg1l_GkvGsfbbkA.png" /></figure><p><em>Dramatically reduce database load and speed up your Laravel applications with simple model caching</em></p><p>When building Laravel applications, database performance often becomes a bottleneck as your user base grows. Repeated queries for the same data waste precious resources and slow down your application. Implementing a caching solution sounds simple in theory, but in practice, it requires careful management of cache invalidation, key generation, and integration with your existing codebase.</p><p>Enter Laravel Model Cache, a package that elegantly solves these problems while requiring minimal changes to your existing code. In this article, I’ll show you how this package can transform your application’s performance with just a few lines of code.</p><h4>The Problem: Database Queries Are Expensive</h4><p>Consider a typical Laravel application with an e-commerce product catalog. Your homepage might display featured products, bestsellers, and recent arrivals. Each page load might trigger several database queries:</p><pre>// Get featured products<br>$featuredProducts = Product::where(&#39;is_featured&#39;, true)-&gt;get();<br><br>// Get bestsellers<br>$bestsellers = Product::orderBy(&#39;sales_count&#39;, &#39;desc&#39;)-&gt;limit(8)-&gt;get();<br><br>// Get recent arrivals<br>$newArrivals = Product::orderBy(&#39;created_at&#39;, &#39;desc&#39;)-&gt;limit(12)-&gt;get();</pre><p>With even modest traffic of 100 requests per minute, these three queries alone would result in 18,000 database hits per hour. That’s a lot of unnecessary work for your database to handle, especially when the data changes infrequently.</p><h4>Traditional Solutions and Their Drawbacks</h4><p>The conventional approach to caching in Laravel looks something like this:</p><pre>$cacheKey = &#39;featured_products&#39;;<br><br>$featuredProducts = Cache::remember($cacheKey, 60, function () {<br>    return Product::where(&#39;is_featured&#39;, true)-&gt;get();<br>});</pre><p>While this works, it introduces several pain points:</p><ol><li><strong>Cache Key Management</strong>: You need to manually create and track unique keys for each query</li><li><strong>Cache Invalidation</strong>: When a product is updated, you need to manually clear relevant caches</li><li><strong>Code Duplication</strong>: Wrapping every query with cache logic adds boilerplate code</li><li><strong>Inconsistent Implementation</strong>: Developers might forget to add caching to new queries</li></ol><h4>Introducing Laravel Model Cache</h4><p>The Laravel Model Cache package by YMigVal takes a fundamentally different approach. Instead of manually wrapping queries in cache logic, it replaces Laravel’s query builder with a cache-aware version that automatically handles caching for all queries.</p><blockquote>Package GitHub Repository: <a href="https://github.com/ymigval/laravel-model-cache">https://github.com/ymigval/laravel-model-cache</a></blockquote><h4>How It Works: Under the Hood</h4><p>The package works by:</p><ol><li>Adding a trait to your Eloquent models</li><li>Intercepting query execution with a custom query builder</li><li>Automatically generating cache keys based on the query structure</li><li>Invalidating cache when models are created, updated, or deleted</li></ol><p>The result is a remarkably simple developer experience with powerful performance benefits.</p><h4>Getting Started in 5 Minutes</h4><p>Let’s walk through setting up Laravel Model Cache in your project:</p><h4>Step 1: Installation</h4><p>First, install the package via Composer:</p><pre>composer require ymigval/laravel-model-cache</pre><h4>Step 2: Publish Configuration (Optional)</h4><p>To customize the package behavior, you can publish the configuration file:</p><pre>php artisan vendor:publish --provider=&quot;YMigVal\LaravelModelCache\ModelCacheServiceProvider&quot; --tag=&quot;config&quot;</pre><p>This creates a config/model-cache.php file with options for:</p><ul><li>Default cache duration in minutes</li><li>Cache key prefix</li><li>Specific cache store selection</li><li>Global toggle to enable/disable caching</li></ul><h4>Step 3: Configure a Cache Driver</h4><p>While the package works best with a cache driver that supports tags (like Redis or Memcached), you can use any cache driver supported by Laravel. The package will automatically adapt to whatever cache driver you’re using.</p><p>Here’s how to configure Redis (recommended for optimal performance):</p><pre>CACHE_STORE=redis<br><br>REDIS_CLIENT=phpredis<br>REDIS_HOST=127.0.0.1<br>REDIS_PASSWORD=null<br>REDIS_PORT=6379</pre><p>You could also use Memcached:</p><pre>CACHE_STORE=memcached<br>MEMCACHED_HOST=127.0.0.1<br>MEMCACHED_PORT=11211</pre><p>Or even the database driver:</p><pre>CACHE_STORE=database</pre><p>Or file driver:</p><pre>CACHE_STORE=file</pre><p>The package includes intelligent fallback mechanisms for file and array drivers that don’t natively support tags. While not as efficient as Redis or Memcached, they’ll still work for basic caching functionality.</p><h4>Step 4: Add the Trait to Your Models</h4><p>Now, simply add the HasCachedQueries trait to any model you want to cache:</p><pre>&lt;?php<br><br>namespace App\Models;<br><br>use Illuminate\Database\Eloquent\Model;<br>use YMigVal\LaravelModelCache\HasCachedQueries;<br><br>class Product extends Model<br>{<br>    use HasCachedQueries;<br>    <br>    // Optionally customize the cache duration for this model<br>    protected $cacheMinutes = 60; // 1 hour<br>    <br>    // Optionally override the global prefix from config<br>    protected $cachePrefix = &#39;products_&#39;;<br>}</pre><p>That’s it! With this simple setup, all queries on the Product model will automatically use the cache. The best part? You don&#39;t need to change any of your existing query code.</p><h4>Real-World Performance Improvements</h4><p>To understand the impact of Laravel Model Cache, I tested a simple product catalog application with and without the package enabled. Here are the results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/853/1*70BuW6nBeNoUT89rErh4uQ.png" /></figure><p>The performance gains are substantial, and they scale with traffic. The more your application is used, the more you benefit from caching.</p><h4>Beyond Basic Caching: Advanced Features</h4><h4>1. Implicit vs Explicit Caching Methods</h4><p>The package offers two complementary approaches to caching:</p><p><strong>Implicit Caching (Standard Eloquent Methods)</strong></p><p>When your model uses the HasCachedQueries trait, standard Eloquent methods automatically use the cache:</p><pre>// This automatically uses the cache with default duration<br>$posts = Post::where(&#39;published&#39;, true)-&gt;get();<br><br>// This also uses the cache<br>$post = Post::where(&#39;id&#39;, 1)-&gt;first();</pre><p><strong>Explicit Caching Methods</strong></p><p>For more explicit control and code readability, use the dedicated caching methods:</p><pre>// Explicitly get results from cache<br>$posts = Post::where(&#39;published&#39;, true)-&gt;getFromCache();<br><br>// Explicitly get first result from cache<br>$post = Post::where(&#39;id&#39;, 1)-&gt;firstFromCache();</pre><p>Both approaches produce the same result — they check the cache first and only hit the database if needed. There’s no performance difference between them; it’s purely about code readability and preference.</p><h4>2. Custom Cache Duration for Specific Queries</h4><p>You can customize the cache duration for individual queries:</p><pre>// Remember for 30 minutes<br>$trendingProducts = Product::where(&#39;trending&#39;, true)<br>    -&gt;remember(30)<br>    -&gt;get();<br>    <br>// Or with explicit caching<br>$featuredProducts = Product::where(&#39;status&#39;, &#39;featured&#39;)<br>    -&gt;remember(15)<br>    -&gt;getFromCache();</pre><h4>3. Disabling Cache When Needed</h4><p>For admin panels or situations where you need fresh data, you can easily bypass the cache:</p><pre>// Skip cache for this query<br>$freshData = Product::withoutCache()-&gt;get();</pre><h4>4. Enhanced Relationship Support</h4><p>The package now includes a new ModelRelationships trait that provides enhanced support for cache invalidation when working with Eloquent relationships:</p><pre>&lt;?php<br><br>namespace App\Models;<br><br>use Illuminate\Database\Eloquent\Model;<br>use YMigVal\LaravelModelCache\HasCachedQueries;<br>use YMigVal\LaravelModelCache\ModelRelationships;<br><br>class Product extends Model<br>{<br>    use HasCachedQueries, ModelRelationships;<br>    <br>    public function categories()<br>    {<br>        return $this-&gt;belongsToMany(Category::class);<br>    }<br>}</pre><p>This trait ensures that your cache is automatically invalidated when manipulating relationships:</p><pre>// These operations will automatically flush the cache<br>$product-&gt;categories()-&gt;attach(1);<br>$product-&gt;categories()-&gt;detach([2, 3]);<br>$product-&gt;categories()-&gt;sync([1, 4, 5]);</pre><p>It also provides convenience methods for explicit cache control:</p><pre>// Sync a relationship and flush cache<br>$product-&gt;syncRelationshipAndFlushCache(&#39;categories&#39;, [1, 2, 3]);<br><br>// Attach records and flush cache<br>$product-&gt;attachRelationshipAndFlushCache(&#39;categories&#39;, [4, 5], [&#39;featured&#39; =&gt; true]);<br><br>// Detach records and flush cache<br>$product-&gt;detachRelationshipAndFlushCache(&#39;categories&#39;, [1, 3]);</pre><h4>5. Selective Caching with Relations</h4><p>You can even control caching behavior for relationship queries:</p><pre>// Cache products but load reviews fresh<br>$products = Product::with([&#39;reviews&#39; =&gt; function($query) {<br>    $query-&gt;withoutCache(); // Skip cache for this relation<br>}])-&gt;get();</pre><h4>Cache Invalidation: The Hard Problem Solved</h4><p>One of the trickiest aspects of caching is knowing when to invalidate the cache. Laravel Model Cache handles this automatically by:</p><ol><li>Listening for model events (created, updated, deleted, restored)</li><li>Using intelligent tagging to invalidate only related cache entries</li><li>Providing commands to manually flush cache when needed</li></ol><p>For example, when a product is updated:</p><pre>$product = Product::find(1);<br>$product-&gt;price = 29.99;<br>$product-&gt;save();</pre><p>The package automatically detects this change and invalidates any cache entries that might contain this product. No manual cache clearing is needed!</p><h4>Advanced Cache Management Tools</h4><h4>Command Line Cache Clearing</h4><p>For situations like data imports or batch operations, you can use the new Artisan command to clear cache:</p><pre># Clear cache for a specific model<br>php artisan mcache:flush &quot;App\Models\Product&quot;<br><br># Clear cache for all models<br>php artisan mcache:flush</pre><h4>Programmatic Cache Control</h4><p>You can also clear the cache programmatically in your application code:</p><pre>// Clear cache for a single model instance<br>$product = Product::find(1);<br>$product-&gt;flushCache();<br><br>// Clear cache for an entire model class<br>Product::flushModelCache();</pre><h4>Advanced Caching Strategies</h4><h4><strong>Using Query Scopes with Caching</strong></h4><p>Combine Laravel scopes with cache settings for reusable cached queries:</p><pre>// In your model<br>public function scopePopular($query)<br>{<br>    return $query-&gt;where(&#39;views&#39;, &#39;&gt;&#39;, 1000)<br>                -&gt;orderBy(&#39;views&#39;, &#39;desc&#39;)<br>                -&gt;remember(60); // Cache popular posts for 1 hour<br>}<br><br>// In your controller - both work the same<br>$products = Product::popular()-&gt;get(); // Implicit<br>$products = Product::popular()-&gt;getFromCache(); // Explicit</pre><h4>Conditional Caching</h4><p>Dynamically decide whether to cache based on conditions:</p><pre>$minutes = $user-&gt;isAdmin() ? 5 : 60; // Less cache time for admins who need fresh data<br>$products = Product::latest()-&gt;remember($minutes)-&gt;get();</pre><h4>Implementation Strategies for Existing Projects</h4><h4>Strategy 1: Gradual Implementation</h4><p>For large existing projects, you might want to implement caching gradually:</p><ol><li>Start with your most frequently accessed models</li><li>Monitor performance improvements</li><li>Gradually add the trait to other models</li></ol><h4>Strategy 2: Performance-Critical Models Only</h4><p>If you’re concerned about cache storage usage, focus on models that:</p><ol><li>Are frequently queried</li><li>Change infrequently</li><li>Are expensive to retrieve from the database</li></ol><h4>Strategy 3: Different Cache Durations by Model Type</h4><p>Adjust cache durations based on how frequently each model type changes:</p><pre>// Product catalog - changes infrequently<br>class Product extends Model<br>{<br>    use HasCachedQueries;<br>    protected $cacheMinutes = 60; // 1 hour<br>}<br><br>// Inventory levels - change frequently<br>class Inventory extends Model<br>{<br>    use HasCachedQueries;<br>    protected $cacheMinutes = 5; // 5 minutes<br>}</pre><h4>Common Pitfalls and Solutions</h4><h4>Pitfall 1: Understanding Cache Driver Limitations</h4><p><strong>Solution</strong>: While Laravel Model Cache works with any cache driver, be aware that non-tag-supporting drivers (like file or database) will use different invalidation strategies. The package handles this automatically, but tag-supporting drivers like Redis or Memcached will offer more selective and efficient cache invalidation.</p><h4>Pitfall 2: Cache Not Being Invalidated</h4><p><strong>Solution</strong>: Verify you’re using Eloquent methods (not Query Builder) for updates to ensure model events are firing. If using relationships, add the ModelRelationships trait for improved cache invalidation with pivot operations.</p><h4>Pitfall 3: Over-Caching Dynamic Content</h4><p><strong>Solution</strong>: Use shorter cache durations or disable caching for highly dynamic data. The withoutCache() method gives you precise control when needed.</p><h4>Pitfall 4: Cache Not Being Used</h4><p>If your queries are not being cached:</p><ol><li>Verify that your model correctly uses the HasCachedQueries trait</li><li>Check that you’re using a compatible cache driver</li><li>Make sure that model-cache.enabled is set to true in your configuration</li></ol><h4>Closing Thoughts: The Right Way to Cache</h4><p>Laravel Model Cache stands out from other caching solutions because it:</p><ol><li><strong>Integrates Seamlessly</strong>: Works with your existing query patterns</li><li><strong>Handles Complexity</strong>: Manages cache invalidation automatically</li><li><strong>Requires Minimal Code</strong>: Just add one trait and you’re done</li><li><strong>Scales Gracefully</strong>: Performance benefits increase with traffic</li><li><strong>Offers Flexibility</strong>: Choose between implicit and explicit caching approaches</li><li><strong>Supports Relationships</strong>: Now with enhanced support for belongsToMany relations</li></ol><p>For many Laravel applications, especially those experiencing database performance issues, this package offers one of the biggest performance improvements for the least amount of effort.</p><p>By implementing Laravel Model Cache, you can dramatically reduce database load, improve response times, and create a better user experience — all without rewriting your application logic.</p><p><em>Are you using caching in your Laravel applications? Have you tried Laravel Model Cache or similar solutions? Share your experiences in the comments below.</em></p><p><em>If you found this article helpful, follow me for more insights on Laravel performance optimization and modern web development techniques.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=048d9e7bbb3e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>