flutter_perf_guard 1.0.0
flutter_perf_guard: ^1.0.0 copied to clipboard
Enterprise-grade Flutter performance analysis, debugging, profiling, and optimization toolkit for production-scale applications. Includes frame analysis, jank detection, memory leak detection, rebui [...]
Changelog #
All notable changes to flutter_perf_guard will be documented in this file.
The format follows Keep a Changelog, and this project adheres to Semantic Versioning.
1.0.0 – 2026-05-21 #
Added #
Core Infrastructure
DiagnosticsEventBus– centralized RxDartPublishSubject-backed event bus with typed streams (frameEvents,memoryEvents,rebuildEvents,jankEvents,criticalEvents)PerformanceEventabstract base class withid,timestamp,source,severityfieldsEventSeverityenum (info,warning,critical)PerfGuardConfigconfiguration value object with presets (minimal,full)PerfGuardsingleton entry point with lifecycle management (initialize,pause,resume,dispose)
Frame Profiling
FrameProfiler– hooks intoSchedulerBinding.addTimingsCallbackfor zero-overhead per-frame metrics collectionFrameMetricsvalue object with build/raster/total durations, FPS,buildFraction,rasterFractionFrameEventtyped event withisJankandisSlowflags- Rolling frame history buffer (configurable size)
- Current FPS with configurable sliding window size
Jank Detection
JankEventemitted when ≥ N consecutive jank frames detected- Configurable
jankThreshold(default 16ms) andconsecutiveJankFramesThreshold(default 3) - Dropped frame count estimation
- Worst and average frame duration in jank sequence
Memory Profiling
MemoryProfiler– periodicdeveloper.NativeRuntime.memoryUsagesamplingMemoryMetricsvalue object with heap used/capacity, external, RSS, GC countMemoryEventwithleakSuspectedflag andallocationDelta- Leak detection via 10-sample sliding-window linear regression (slope > 512 KB/sample triggers alert)
- Configurable
memorySamplingInterval,memoryWarningThreshold,memoryCriticalThreshold
Rebuild Tracking
RebuildTracker– debug-only instrumentation viadebugOnRebuildDirtyWidgetRebuildMetricswith rebuild count, total/average time, rebuild rate,hasRepaintBoundary,triggeredBySetStateRebuildEventwithisUnnecessarydetection heuristic- Hot widget ranking (top 20 by rebuild count)
- Excessive rebuild detection (> 60 rebuilds/s)
- Automatic pruning of old widget records
Widget Location Tracking
RebuildLocation– captures file name, line number, and full ancestor path for rebuilding widgets (debug mode only)RebuildMetrics.locationfield automatically captured on first rebuild- Ancestor path collection via
visitAncestorElements - Debug-only file extraction support
- Release/profile mode fallback note:
"run in debug mode to see file location"
Timeline Recording
TimelineRecorder– subscribes to all events and maintains circular buffer- Configurable
maxEntries exportJson(pretty: bool)for DevTools-compatible outputentriesByType()filtering helper
Benchmark Engine
BenchmarkSuitewithadd()(sync) andaddAsync()methodsBenchmarkEntrysupporting sync and async bodiesBenchmarkRunnerwith configurable warmup and measured run countsBenchmarkResultwith mean, median, p95, p99, min, max, stddev, ops/srunAll()for multi-suite execution- Full
toJson()serialization
Startup Analysis
StartupAnalyzerwith milestone tracking:markAppStart,markFirstFrame,markNavigatorReady,markDataLoaded,markInteractivetimeToFirstFrametimeToInteractive
Navigation Tracking
NavigationTrackerextendsNavigatorObserver- Records push/pop/replace transitions with duration
isSlowflag for transitions > 300ms
Network Request Profiling
NetworkProfiler– hooks intoHttpOverrides.globalto intercept app HTTP traffic- Records URL, method, status code, duration, response size, timestamp, and errors
slowRequests(> 1 second)failedRequests(status ≥ 400 or thrown errors)- Human-readable summaries with optimization suggestions
- Optional enablement via
PerfGuardConfig(enableNetworkProfiler: true)
Async Operation Profiling
AsyncProfiler– tracks named sync/async operationstrack()andtrackSync()wrappers- Records duration, timestamps, and failures
- Slow operation detection via configurable threshold
- Human-readable summaries with optimization suggestions
Image Cache Analysis
ImageCacheAnalyzer– readsPaintingBinding.instance.imageCache- Reports:
- current image count
- live image count
- cache size
- usage percentage
trimCacheTo(int maxBytes)clearCache()- Included in exports automatically
Performance Grading
PerformanceGrader– grades categories A–F with emoji indicators- Categories:
- Frames
- Memory
- Rebuilds
- Navigation
- Overall grade derived from worst category
- Human-readable summaries:
frameSummary()memorySummary()rebuildSummary()navigationSummary()
Visualization
-
PerfGuardOverlay– lightweight in-app HUD showing:- FPS
- build/raster durations
- memory
- jank alerts
-
Overlay rendered via
CustomPainter -
OverlayAlignmentenum:- topLeft
- topRight
- bottomLeft
- bottomRight
-
DiagnosticsDashboardfull-screen diagnostics UI with tabs:- FRAMES
- MEMORY
- REBUILDS
- LOG
-
_FrameChartPainter -
_MemoryChartPainter
Export & Reporting
ProfilingReportfull-session snapshot modelReportExporter- JSON export support
- Plain-text
.txtreport generation ReportFormatenum:textjson
- Optimization suggestion generation:
- repaint boundary suggestions
- rebuild reduction suggestions
- memory pressure warnings
- Rebuild reports include file locations and ancestor paths
autoExportOnCriticaloption
File Writing
- Conditional import pair:
file_writer.dartfile_writer_web.dart
- Native export via
path_provider - Web fallback returns content string directly
Analysis Models
JankReport+JankSegmentRepaintReport+RepaintZoneLayoutReport+LayoutHotspot
Tests
-
Unit tests:
FrameMetricsMemoryMetricsRebuildMetricsDiagnosticsEventBusBenchmarkResult
-
Rendering tests:
PerfGuardOverlay
-
Stress tests:
- event bus throughput
- concurrent subscribers
- timeline buffer limits
- benchmark correctness
Documentation
README.mddoc/architecture_guide.mddoc/profiling_guide.mddoc/optimization_guide.mddoc/benchmark_guide.mddoc/diagnostics_guide.md
Example App
- Overlay HUD demo
- Dashboard navigation demo
- Jank simulation
- Memory pressure simulation
- Rebuild storm simulation
- Benchmark execution demo
- Report export demo
Platform Support #
- Android ✅
- iOS ✅
- Web ✅
- macOS ✅
- Windows ✅
- Linux ✅