Learn/Testing & Debugging/Performance Debugging

Performance Debugging

Profile and fix jank, slow builds, and memory issues with DevTools

8 min~5 min read+50 FX

You can read this lesson publicly. Sign in to unlock exercises, quiz, and FX progress tracking.

Table of Contents

  1. 1. Performance Budget By Feature
  2. 2. This Lesson In Simple Words
  3. 3. Your level focus
  4. 4. One practical habit
  5. 5. Deep Understanding Guide
  6. 6. Why this lesson matters
  7. 7. Study flow for better retention
  8. 8. Quick Glossary
  9. 9. Architecture Lens

Having trouble? AI is here to help

Ask context-aware questions about this lesson. Free plan: 5 questions/day. Upgrade to Premium for higher daily limits.

Use the AI button at the bottom of the screen

Performance Debugging

A smooth Flutter app targets 60 frames per second (or 120 on high-refresh displays). When your app drops frames, users experience jank, which is the visible stutter or lag during animations and scrolling. Performance debugging involves identifying which frames are slow, understanding whether the bottleneck is in the UI thread or the raster thread, and applying targeted optimizations. Flutter DevTools provides a comprehensive Performance view that makes this diagnosis systematic.

dart
1// ══════════════════════════════════════
2// PERFORMANCE DEBUGGING WITH DEVTOOLS
3// ══════════════════════════════════════
4
5// ── Step 1: Run in Profile Mode ──
6// NEVER profile in debug mode (it is too slow)
7// flutter run --profile
8
9// ── Step 2: Open DevTools Performance Tab ──
10// In terminal press 'v' to open DevTools
11// Or: VS Code → Run → Open DevTools → Performance
12
13// ── Step 3: Record a Timeline ──
14// 1. Click "Record" in Performance view
15// 2. Perform the slow action (scroll, navigate, animate)
16// 3. Click "Stop"
17// 4. Analyze the frame chart:
18// - Green bar = frame rendered under 16ms (good)
19// - Red bar = frame took too long (jank!)
20// - UI thread = Dart code execution
21// - Raster thread = GPU rendering
22
23// ── UNDERSTANDING THE FRAME BUDGET ──
24// 60 FPS = 16.67ms per frame
25// If UI thread > 16ms → your Dart code is too slow
26// If Raster thread > 16ms → too many pixels to paint
27
28// ── Step 4: Find the Bottleneck ──
29// Click on a red (slow) frame to see:
30// - Which widgets were rebuilt
31// - How long each build() took
32// - Which painting operations were expensive
dart
1// ══════════════════════════════════════
2// COMMON PERFORMANCE PROBLEMS AND FIXES
3// ══════════════════════════════════════
4
5// ── PROBLEM 1: Unnecessary Rebuilds ──
6// Symptom: Too many widgets rebuilding on every frame
7
8// BAD: Entire tree rebuilds when counter changes
9class MyPage extends StatefulWidget { ... }
10class _MyPageState extends State<MyPage> {
11 int _counter = 0;
12
13 @override
14 Widget build(BuildContext context) {
15 return Column(
16 children: [
17 ExpensiveHeader(), // rebuilds unnecessarily!
18 Text('$_counter'),
19 ExpensiveFooter(), // rebuilds unnecessarily!
20 ],
21 );
22 }
23}
24
25// FIX: Extract widgets, use const, or use Consumer/Selector
26class _MyPageState extends State<MyPage> {
27 int _counter = 0;
28
29 @override
30 Widget build(BuildContext context) {
31 return Column(
32 children: [
33 const ExpensiveHeader(), // const prevents rebuild
34 Text('$_counter'),
35 const ExpensiveFooter(), // const prevents rebuild
36 ],
37 );
38 }
39}
40
41// ── PROBLEM 2: Heavy Work on UI Thread ──
42// Symptom: UI freezes during computation
43
44// BAD:
45void processData() {
46 final result = heavyComputation(bigDataSet); // blocks UI!
47 setState(() => _result = result);
48}
49
50// FIX: Use compute() for isolate-based processing
51import 'package:flutter/foundation.dart';
52
53void processData() async {
54 final result = await compute(heavyComputation, bigDataSet);
55 setState(() => _result = result);
56}
57
58// ── PROBLEM 3: Expensive List Rendering ──
59// BAD: Creates ALL items at once
60ListView(
61 children: List.generate(10000, (i) => ListTile(title: Text('Item $i'))),
62)
63
64// FIX: Use .builder for lazy rendering
65ListView.builder(
66 itemCount: 10000,
67 itemBuilder: (_, i) => ListTile(title: Text('Item $i')),
68)
dart
1// ── PROBLEM 4: Memory Leaks ──
2// Symptom: App gets slower over time, eventual crash
3
4// Common causes:
5// a) Stream subscriptions not cancelled
6class _MyState extends State<MyWidget> {
7 late StreamSubscription _sub;
8
9 @override
10 void initState() {
11 super.initState();
12 _sub = myStream.listen((data) => setState(() => _data = data));
13 }
14
15 @override
16 void dispose() {
17 _sub.cancel(); // ALWAYS cancel subscriptions
18 super.dispose();
19 }
20}
21
22// b) AnimationController not disposed
23// c) TextEditingController not disposed
24// d) ScrollController not disposed
25// Rule: If you create it in initState, dispose it in dispose()
26
27// ── PERFORMANCE CHECKLIST ──
28// 1. Use const constructors wherever possible
29// 2. Use ListView.builder instead of ListView with children
30// 3. Avoid calling setState on the entire page
31// 4. Move heavy computation to isolates with compute()
32// 5. Cache network images with CachedNetworkImage
33// 6. Use RepaintBoundary around expensive custom painters
34// 7. Profile in --profile mode, NEVER in debug mode
35// 8. Dispose ALL controllers and subscriptions
36// 9. Use the Performance Overlay to spot jank visually:
37// MaterialApp(showPerformanceOverlay: true)
38
39// ── MEMORY DEBUGGING ──
40// Open DevTools → Memory tab
41// 1. Take a heap snapshot
42// 2. Perform actions in the app
43// 3. Take another snapshot
44// 4. Compare to find objects that should have been freed
45// 5. Look for growing collections, unreleased streams

Quick Performance Test

💡 Quick Performance Test

Add showPerformanceOverlay set to true in your MaterialApp to display a real-time performance graph directly on the screen. The top bar shows raster thread timing and the bottom shows UI thread timing. Any bar that exceeds the green line is a dropped frame. This is the fastest way to spot jank without opening DevTools.

Performance Budget By Feature

Assign a performance budget for each critical flow:

  • Navigation transitions remain under frame budget on target devices.
  • First meaningful list render stays within acceptable startup latency.
  • Scrolling remains stable with realistic data volumes.
  • Memory growth remains bounded during repeated navigation loops.

Feature-level budgets turn performance from guesswork into an enforceable quality target.

Performance Investigation Checklist

  • Profiling is performed in profile mode on representative hardware.
  • Slow frames are classified as UI-thread or raster-thread bottlenecks.
  • Rebuild hotspots are measured before and after optimization.
  • Heavy compute work is moved off UI thread where appropriate.
  • Controllers and subscriptions are disposed to prevent long-session degradation.

This Lesson In Simple Words

Profile and fix jank, slow builds, and memory issues with DevTools. Forms collect user input, and validation ensures the input is safe and useful.

Your level focus

Think in architecture, reliability, and team-level maintainability.

One practical habit

Show validation messages early and clearly, near the field that needs correction.

Deep Understanding Guide

Why this lesson matters

Most app trust problems start when invalid or incomplete input reaches backend systems.

Study flow for better retention

  1. Separate UI, state, and data boundaries before writing implementation details.
  2. Treat forms as mini workflows: input, validate, submit, and recover from errors.
  3. If another developer can read your flow quickly, your design choices are clear.

Common Mistakes To Avoid

  • Validating only on submit and giving late feedback to users.
  • Using vague error text that does not tell users what to fix.
  • Forgetting to trim whitespace and normalize input values.
  • Not handling keyboard focus flow and accessibility labels.

Practice Sprint (15-25 Minutes)

  • Before running sample code, predict output and behavior in one sentence.
  • Build a signup form with per-field validators and submit-state handling.
  • Add password strength feedback with friendly, actionable hints.
  • Simulate a server validation error and show a user-safe message.
  • Complete the required exercises without using hints on the first attempt.
  • Answer this question out loud before checking quiz options: "Why should you NEVER profile performance in debug mode?".

Quick Glossary

  • build: The method that describes UI for the current state.
  • animation: Controlled change in UI properties over time.
  • devtools: Flutter tooling suite for debugging and performance analysis.

Code Comprehension Drill

  • State the purpose of the code block in one line before reading details.
  • Mark inputs, state changes, and final output.
  • Change one small value and predict what should happen before running.
  • Run again and compare your prediction with actual behavior.

Architecture Lens

Validated input at UI and domain layers protects business logic from invalid assumptions.

As your app grows, keep UI, state, and data responsibilities separate so each part stays testable and easier to modify.

Lesson Completion Checklist

  • I can explain "Performance Debugging" in simple words without reading notes.
  • I can describe one real app situation where this concept is required.
  • I know at least one mistake to avoid: Validating only on submit and giving late feedback to users.
  • I can modify one code sample and correctly predict the behavior change.
  • I can finish required exercises with understanding, not trial-and-error guesses.

Frequently Asked Questions

Why should you NEVER profile performance in debug mode?

Debug mode includes extra checks, assertions, and disables optimizations. This makes everything slower than release and produces inaccurate performance data. Always use --profile mode.

What is the frame budget for a 60 FPS app?

60 frames per second means each frame has approximately 16.67 milliseconds to complete both the UI thread (build/layout) and the raster thread (paint/composite).

How do you move heavy computation off the UI thread?

async/await still runs on the UI thread. compute() spawns a separate Dart isolate for CPU-intensive work, keeping the UI thread free for smooth rendering.

Suggest Improvement

Something seems incorrect, unclear, or missing? Let us know.

About The Author

FlutterCraft editorial lessons are reviewed by experienced Flutter developers and updated to stay aligned with modern Flutter and Dart best practices.

Reference docs: Flutter Documentation, Dart Language Tour, and official package documentation where relevant.

Sign in to continue with exercises and quiz for this lesson.

Sign In to Continue