Skip to content
Tutorials Center
My learning

Topics

Lesson 56 of 73 ยท Quality and performance

Performance and DevTools

Make Flutter apps smooth: the 16 ms frame budget, const widgets, rebuild profiling, jank, Impeller and shader compilation, memory leaks and Flutter DevTools.

Users do not read frame timings, but they feel them. A list that stutters while scrolling, a button that answers a quarter-second late, an app that gets slower the longer it stays open: all of these are performance bugs. Flutter is fast by default, and most apps never need heroic tuning. What they need is a few habits and the ability to measure before changing anything.

This lesson explains the frame budget, the common causes of jank, how to cut needless rebuilds, how Impeller changed shader problems, how to find memory leaks, and how to use Flutter DevTools.

Real vs stand-in. Dart code and DevTools workflows are real but read-only, because the site has no Flutter runtime or profiler. The live examples are JavaScript stand-ins: a frame-budget calculator and a rebuild counter that mimic what you would see in DevTools.

The frame budget

60 fps About 16.7 ms per frame.
120 fps About 8.3 ms per frame.
Miss it The frame is late. That is jank.

Build and raster each get part of the budget.

1 / 2

The frame budget

The screen refreshes at a fixed rate. At 60 Hz a new image is needed every 1000 / 60 โ‰ˆ 16.7 ms; on a 120 Hz phone the window is 8.3 ms. Flutter has two threads of interest for each frame:

  • The UI thread runs your Dart code: build methods, layout and painting instructions. This is where your code can be slow.
  • The raster thread turns those instructions into pixels on the GPU. It is slow when the scene is too heavy: large blurs, many layers with saveLayer, huge images.

If either one takes longer than the budget, a frame is dropped and the animation visibly hitches. That hitch is jank. Occasional slow frames at startup are normal; sustained slow frames while scrolling are the ones to fix.

JS Which frames miss the budget?

Press Run (or Ctrl + Enter) to see the console output here.

No output.

At 120 Hz frame 8 (11.5 ms) becomes janky too, although it was fine at 60 Hz, because the budget halves. Frames 4 and 6 are bad on both: one is a UI-thread problem (too much Dart work), the other a raster-thread problem (too heavy to draw). Knowing which thread is slow decides the fix, which is why you profile before guessing.

Profile the right way

Performance numbers from debug mode are meaningless: debug builds run unoptimized code with extra checks. Use profile mode on a real device:

Terminal
flutter run --profile

Then open Flutter DevTools, a set of browser-based tools that connect to the running app:

Tool Use it to
Performance See a timeline of frames, find slow ones, and see whether UI or raster is the problem
CPU profiler Find the Dart functions that take the most time
Memory Watch heap size, take snapshots and find leaks
Widget inspector See the widget tree, and optionally highlight rebuilds
Network Inspect HTTP requests
Logging Read logs and framework events

A good loop: record a timeline while you scroll the slow screen, select a red frame, read which phase was long, fix, record again.

Reduce rebuilds

build can run many times per second, so it must be cheap and must not run more than needed. Rebuilds are not bad by themselves (the tree lesson explains why widgets are cheap), but rebuilding a large subtree on every tick adds up.

1. Use const. A const widget is created once at compile time and Flutter can skip rebuilding it, because the same instance is passed again.

DART
Column(
  children: const [
    Icon(Icons.star),
    SizedBox(height: 8),
    Text('Rated by 2,000 readers'),
  ],
)

The analyzer rule prefer_const_constructors points out every missed chance.

2. Push setState down. If only a counter changes, make a small stateful widget for the counter rather than calling setState on the whole page (see setState).

3. Listen narrowly. With Provider use select, with Riverpod use select or smaller providers, and with ValueListenableBuilder wrap only the part that changes (lifting state, Provider).

4. Extract widgets, not helper methods. A method like Widget _buildHeader() is rebuilt whenever its parent is. A separate const Header() widget class can be skipped entirely.

5. Do not do heavy work in build. Sorting a 5,000-item list, parsing JSON or creating a controller inside build repeats the work every rebuild. Compute once (in initState, in your state class, or memoized) and read the result in build.

DART
// Slow: sorts on every rebuild.
Widget build(BuildContext context) {
  final sorted = [...items]..sort((a, b) => a.name.compareTo(b.name));
  return ListView(children: [for (final i in sorted) Text(i.name)]);
}

// Better: sort when the data changes.
void _setItems(List<Item> items) {
  setState(() {
    _sorted = [...items]..sort((a, b) => a.name.compareTo(b.name));
  });
}

Stand-in: a rebuild counter

The widget inspector can show rebuild counts; here we reproduce the idea. A tree with a counter inside a big page is updated 100 times, once with the state at the top of the tree and once with state pushed down into the counter.

JS Counting rebuilds: top-level state vs pushed down

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Moving state down (B) is the most effective; making the heavy subtree const (C) gets part of the way when the state has to stay high. In real Flutter, const skips a subtree because the framework sees an identical widget instance and does not rebuild its element.

Lists, images and layout

  • Use builders for long lists. ListView.builder creates only the visible items (ListView, GridView and Slivers). A Column inside a SingleChildScrollView with 1,000 children builds them all.
  • Give list items a stable shape. Setting itemExtent or prototypeItem lets the list skip measuring each child.
  • Size images. A 4000 px photo in a 100 px thumbnail still decodes at full size unless you set cacheWidth/cacheHeight or resize it on the server (Fonts, images and assets).
  • Be careful with expensive effects. Opacity over a large animating subtree, ClipRRect with anti-aliasing, BackdropFilter blur and saveLayer are raster-thread heavy. Prefer FadeTransition or a color with alpha, and avoid blur over big areas.
  • Avoid intrinsic layout passes. IntrinsicHeight and IntrinsicWidth need extra layout passes; use them rarely, never in long lists (constraints explains why).

Heavy computation: leave the UI thread

Dart runs your code on one thread per isolate. A 200 ms JSON parse or image filter on the UI isolate blocks every frame for 200 ms. Move such work to another isolate:

DART
final result = await Isolate.run(() => parseHugeJson(text));
// or the Flutter helper:
final result2 = await compute(parseHugeJson, text);

Isolates do not share memory, so the function and its arguments are copied. Do this for work that takes more than a few milliseconds, not for small tasks, where the copying costs more than it saves. Plain async/await does not help here: it only waits without blocking, it does not run your CPU work in parallel (async lesson).

Shader compilation jank and Impeller

Drawing needs GPU programs called shaders. In the old Skia renderer, shaders were compiled the first time an effect was drawn. That compile could take tens of milliseconds, causing a one-time stutter, typically the first run of an animation. The fix at the time was "shader warmup": recording shaders in a test run and bundling them with the app.

Impeller, Flutter's newer renderer, removes the problem by compiling a fixed set of shaders ahead of time when the engine is built, so there is nothing to compile during an animation. It is the default renderer on iOS and on modern Android versions, and it keeps improving. If you still see first-run stutters, check in DevTools whether they come from shader work, image decoding, or your own code, because those look similar on a timeline.

Memory and leaks

Dart has a garbage collector, so "leaks" mean objects that are still referenced when they should be gone. Typical causes in Flutter:

  • A StreamSubscription, Timer, AnimationController, TextEditingController, ScrollController or FocusNode not cancelled or disposed in dispose.
  • A listener added to a ChangeNotifier or ValueNotifier and never removed.
  • A long-lived object (singleton, global list) holding a reference to a BuildContext or a State.
  • Unbounded caches: a map that only ever grows.
DART
class _LiveState extends State<Live> {
  late final StreamSubscription<int> _sub;
  final _controller = TextEditingController();

  @override
  void initState() {
    super.initState();
    _sub = ticker.listen((v) => setState(() => _last = v));
  }

  @override
  void dispose() {
    _sub.cancel();          // stop listening
    _controller.dispose();  // release native resources
    super.dispose();
  }
  // ...
}

To hunt a leak, open the Memory tab, navigate to a screen and back several times, force a garbage collection and look at whether instance counts of that screen's classes keep growing. Newer Flutter versions can also report leaked disposable objects in debug mode with the leak_tracker tooling.

A tuning checklist

  1. Reproduce the problem on a real, mid-range device in profile mode.
  2. Record a timeline and decide: UI thread, raster thread, or one-time (shader, decode)?
  3. UI thread: reduce rebuild scope, add const, move work out of build, use isolates for heavy compute.
  4. Raster thread: simplify effects, shrink images, avoid saveLayer-heavy widgets.
  5. Re-measure. If nothing changed, undo the change.

Premature optimization is waste; unmeasured optimization is guessing. Next up is making your app usable by everyone: Accessibility and Internationalization.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Roughly how long is the frame budget at 60 frames per second?

    1000 ms / 60 is about 16.7 ms. At 120 fps it halves to about 8.3 ms.
  2. 2. Why should you measure performance in profile mode instead of debug mode?

    Debug builds are much slower than release-like builds. Profile mode is close to release but still allows DevTools.
  3. 3. Which change most directly reduces rebuilds when only a small label changes?

    setState rebuilds the State's whole build method. A small stateful widget limits the rebuild to itself.
  4. 4. A 300 ms JSON parsing step freezes scrolling. What is the right fix?

    async only waits; CPU-heavy work still blocks the UI isolate. A separate isolate runs it in parallel.
  5. 5. Which of these is a common cause of a memory leak in a State class?

    An undisposed subscription or controller keeps references alive and keeps working after the screen is gone.

Summary

  • Each frame has a budget of about 16.7 ms at 60 Hz and 8.3 ms at 120 Hz, split between the UI thread (your Dart code) and the raster thread (drawing).
  • Profile on a real device in profile mode with DevTools; find out which thread is slow before changing code.
  • Cut rebuilds with const, small stateful widgets, narrow listeners, extracted widget classes and no heavy work in build.
  • Use builder lists, sized images, and cheap effects; send heavy computation to isolates.
  • Impeller precompiles shaders, which removes most first-run shader jank.
  • Dispose controllers, cancel subscriptions and remove listeners to avoid leaks.

Next: Accessibility and Internationalization