This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilehigh PriorityID: flutter-custom-painter-repaint-boundary

Flutter CustomPainter RepaintBoundary & Canvas Cache Standard

Performance standard for Flutter rendering and canvas animations. Mandates wrapping CustomPaint widgets in RepaintBoundary to isolate canvas repaints from the outer widget tree, implementing shouldRepaint() equality checks, and eliminating 60fps frame drops in custom charts and particle animations.

Prohibited Anti-Pattern: AI omits RepaintBoundary and unconditionally returns `true` in CustomPainter.shouldRepaint, causing Flutter to repaint the entire screen on every cursor blink or tick.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Flutter CustomPainter RepaintBoundary & Canvas Cache Standard - Performance standard for Flutter rendering and canvas animations. Mandates wrapping CustomPaint widgets in RepaintBoundary to isolate canvas repaints from the outer widget tree, implementing shouldRepaint() equality checks, and eliminating 60fps frame drops in custom charts and particle animations.
globs: **/*painter*.dart, **/*canvas*.dart, **/widgets/**/*.dart
alwaysApply: false
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/flutter-custom-painter-repaint-boundary"
---

# Flutter CustomPainter RepaintBoundary & Canvas Cache Standard

> **Severity**: HIGH | **Category**: mobile
> **Anti-Pattern Warning**: AI omits RepaintBoundary and unconditionally returns `true` in CustomPainter.shouldRepaint, causing Flutter to repaint the entire screen on every cursor blink or tick.

## System Constraints
You are a Flutter Rendering Pipeline and Performance Engineer. NEVER render CustomPaint widgets without wrapping them in a RepaintBoundary. NEVER return true unconditionally from shouldRepaint(). Doing so forces the Flutter Skia/Impeller engine to rasterize the entire screen layer repeatedly, causing severe jank and battery drain.

## Strict Guidelines
- MUST wrap CustomPaint with RepaintBoundary to create an isolated Layer and prevent parent repaint cascades.
- MUST implement precise property comparisons in shouldRepaint(covariant MyPainter oldDelegate) instead of returning true.
- MUST reuse Paint() objects as class fields rather than allocating new Paint() instances inside paint() loops.
- MUST NOT allocate new Path() or Color() instances inside high-frequency paint() loops.
- SHOULD use canvas.drawRawPoints or PictureRecorder for rendering complex multi-thousand point data series.

## Bad vs Good Implementations
### Isolating Canvas Rendering with RepaintBoundary in Flutter

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Allocating Paint objects inside the paint() loop triggers thousands of garbage collection cycles, and returning shouldRepaint => true forces rasterization even when progress is unchanged.
```dart
// FATAL: Repainting entire screen on every frame and allocating Paint in loop
class BadChartPainter extends CustomPainter {
  final double progress;
  BadChartPainter(this.progress);

  @override
  void paint(Canvas canvas, Size size) {
    // ALLOCATION IN LOOP: Causes heavy GC pressure on every animation tick!
    final paint = Paint()..color = Colors.blue..strokeWidth = 3;
    canvas.drawLine(Offset.zero, Offset(size.width * progress, size.height), paint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => true; // Always repaints!
}
```

#### Production Standard (Correct)
> **Standard**: Wraps the CustomPaint in a RepaintBoundary to isolate the display list, caches the Paint instance, and implements precise shouldRepaint diffing for butter-smooth 120 FPS rendering.
```dart
class GoodChartPainter extends CustomPainter {
  final double progress;
  // Reusable paint instance cached on class field
  final Paint _linePaint = Paint()
    ..color = Colors.blue
    ..strokeWidth = 3
    ..style = PaintingStyle.stroke;

  GoodChartPainter(this.progress);

  @override
  void paint(Canvas canvas, Size size) {
    canvas.drawLine(Offset.zero, Offset(size.width * progress, size.height), _linePaint);
  }

  @override
  bool shouldRepaint(covariant GoodChartPainter oldDelegate) {
    // Repaints ONLY when numeric progress value actually changes
    return oldDelegate.progress != progress;
  }
}

// Usage: Isolate layer boundary
Widget buildChart(double progress) {
  return RepaintBoundary(
    child: CustomPaint(
      size: const Size(300, 200),
      painter: GoodChartPainter(progress),
    ),
  );
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Flutter CustomPainter RepaintBoundary & Canvas Cache Standard

Flutter CustomPainter RepaintBoundary & Canvas Cache Standard defines an industrial-grade behavioral standard for mobile engineering. Performance standard for Flutter rendering and canvas animations. Mandates wrapping CustomPaint widgets in RepaintBoundary to isolate canvas repaints from the outer widget tree, implementing shouldRepaint() equality checks, and eliminating 60fps frame drops in custom charts and particle animations. Modern software architectures require strict adherence to deterministic patterns to guarantee high availability, maintainability, and zero security vulnerabilities.

Framework Paradigm Shift & Drift MechanicsLLMs are trained on millions of open-source repositories containing outdated code, legacy idioms, and unpatched antipatterns. When coding assistants generate implementations for this stack, they default to common statistical tokens: AI omits RepaintBoundary and unconditionally returns `true` in CustomPainter.shouldRepaint, causing Flutter to repaint the entire screen on every cursor blink or tick. Without an explicit system instruction file, developers spend hours debugging silent failures.
Failure Modes & Production Blast Radius

Hazard Analysis: What Breaks Without This Rule

The following failure modes have been cataloged from hundreds of hours of production code reviews where AI assistants produced non-compliant implementations:

Failure ModeAI Symptom (The Anti-Pattern)SeverityProduction Impact & Remedy
AI Hallucination & Deprecation DriftAI omits RepaintBoundary and unconditionally returns `true` in CustomPainter.shouldRepaint, causing Flutter to repaint the entire screen on every cursor blink or tick.High
Violating this industrial standard introduces regression bugs, security risks, and unexpected runtime failures in production.
Enforce explicit behavioral system directives across all AI coding assistants in your repository.
Silent Architecture InconsistencyAI assistants produce mixed paradigms across files, creating fragmented codebase conventions.Medium
Increases cognitive load during code reviews and leads to maintenance debt across engineering teams.
Pin project conventions in .cursor/rules, CLAUDE.md, and AGENTS.md so all team agents follow identical guardrails.
Architectural Directives in Detail

Step-by-Step Production Directives

Each rule constraint below is injected into the AI agent's system prompt to establish deterministic boundaries:

1

MUST wrap CustomPaint with RepaintBoundary to create an isolated Layer and prevent parent repaint cascades.

MUST wrap CustomPaint with RepaintBoundary to create an isolated Layer and prevent parent repaint cascades.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
2

MUST implement precise property comparisons in shouldRepaint(covariant MyPainter oldDelegate) instead of returning true.

MUST implement precise property comparisons in shouldRepaint(covariant MyPainter oldDelegate) instead of returning true.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
3

MUST reuse Paint() objects as class fields rather than allocating new Paint() instances inside paint() loops.

MUST reuse Paint() objects as class fields rather than allocating new Paint() instances inside paint() loops.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
4

MUST NOT allocate new Path() or Color() instances inside high-frequency paint() loops.

MUST NOT allocate new Path() or Color() instances inside high-frequency paint() loops.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
5

SHOULD use canvas.drawRawPoints or PictureRecorder for rendering complex multi-thousand point data series.

SHOULD use canvas.drawRawPoints or PictureRecorder for rendering complex multi-thousand point data series.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is Flutter CustomPainter RepaintBoundary & Canvas Cache Standard critical for AI coding assistants?

Performance standard for Flutter rendering and canvas animations. Mandates wrapping CustomPaint widgets in RepaintBoundary to isolate canvas repaints from the outer widget tree, implementing shouldRepaint() equality checks, and eliminating 60fps frame drops in custom charts and particle animations. Without explicit behavioral boundaries, AI coding assistants (Cursor, Claude Code, Windsurf, Codex) rely on training data averages, which frequently produce deprecated, inefficient, or vulnerable code patterns.

Q:How does adopting this rule prevent AI hallucinations?

This rule explicitly declares what the AI must avoid (AI omits RepaintBoundary and unconditionally returns `true` in CustomPainter.shouldRepaint, causing Flutter to repaint the entire screen on every cursor blink or tick.) and prescribes verified positive examples. Grounding the LLM with negative and positive pairs eliminates guesswork.

Q:Which AI coding environments are supported?

This specification is multi-platform compatible: Cursor (.cursor/rules/*.mdc & .cursorrules), Anthropic Claude Code (CLAUDE.md), Windsurf (.windsurfrules), Codex / Cline (AGENTS.md), and GitHub Copilot (.github/copilot-instructions.md).

Q:Can I combine this rule with other technology stacks?

Yes. Use the Interactive Stack Builder or download an Agent Pack to merge this rule with other frontend, backend, database, security, and DevOps rules without syntax collision.

Open Specification · CC BY 4.0·Free for Personal, Team & Commercial In-Repo Use

Citation & Open Source Attribution Guidelines

This specification is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). You are completely free to adapt and share this rule in your workspace. If citing, including in public AI benchmark datasets, or redistributing, attribution to AgentRules.org is required.

Related MOBILE Rules

View all rules →
1 Rule in Stack

Flutter