Flutter performance and rendering
Why it matters
- A
setStatehigh in the tree re-runsbuildfor that widget and everything it creates below. On a large screen that is a lot of wasted work per tap, and it is the most common cause of jank in Flutter apps, just as broad recomposition is in Compose. - Shader compilation jank (a stutter the first time an effect is drawn) was Flutter's best-known performance problem. Impeller, now the default renderer on iOS and on modern Android, was built to remove it, and interviewers expect you to know both why it happened and which devices still use the older renderer.
- Performance must be measured in profile mode on a real device. Debug mode runs unoptimised JIT code with extra checks, so its frame times say little about what users see.
- Senior interviews for cross-platform roles probe whether you can read a DevTools frame chart, tell a UI-thread problem from a raster-thread problem, and pick between
const, smaller rebuild scopes, lazy lists, andRepaintBoundarybased on evidence.
The simple explanation
- Widget tree = the blueprint: cheap, immutable descriptions of what the screen should look like.
- Element tree = the site foreman: keeps the live structure and state, compares each new blueprint with the old one, and decides what to update.
- RenderObject tree = the building itself: does layout (sizes and positions) and paint.
- A
constwidget = a blueprint that is literally the same sheet of paper as last time: the foreman sees it is identical and skips that part. RepaintBoundary= a glass partition: repainting one room does not force the rooms around it to repaint.- Shader jank = mixing a new paint colour on site the first time it is needed: the crew stalls once, then it is instant.
How does Flutter render a frame, and what makes it slow? Flutter keeps three trees:
- Widget tree: immutable configuration objects, rebuilt often. Creating widgets is cheap.
- Element tree: the long-lived instances that hold
State. WhensetStatemarks aStatedirty, itsbuildruns again and the element compares each new child widget with the old one. If the new widget is the identical instance (as aconstwidget is), the element skips that subtree. If the type and key match, it updates the existing element; otherwise it replaces it. - RenderObject tree: the objects that do layout and paint. Only render objects whose properties actually changed are marked for layout or paint.
Each frame runs in two places. The UI thread runs your Dart code: build, layout, paint, which produce a layer tree. The raster thread turns that layer tree into GPU commands using the rendering engine. DevTools shows both, so you can tell whether a slow frame came from your widgets or from expensive drawing.
The engine is Impeller on iOS (the only renderer there) and by default on Android API 29 and newer, where it uses Vulkan or, on some devices, its OpenGL ES backend. Older Android devices use the legacy Skia OpenGL renderer. Impeller compiles its shaders when the engine is built, not while the app runs, which removes shader compilation jank. On the legacy renderer, the first use of an effect such as a blur, a complex shadow, or a clip can still stall the raster thread while a shader compiles.
| Lever | What it changes | Typical mistake |
|---|---|---|
const widgets | An identical instance lets the element skip that subtree | Thinking const on a TextStyle alone stops a rebuild |
| Smaller rebuild scope | setState in a small widget rebuilds only that widget's subtree | Holding all screen state in one top-level State |
ListView.builder | Builds only visible items plus a cache area | ListView(children: [...]) with hundreds of items |
RepaintBoundary | Gives a subtree its own layer so its repaints stay local | Wrapping everything, or adding it where the framework already does |
| Profile mode | AOT-compiled code with realistic timing, plus profiling hooks | Judging performance in debug mode |
Frame budget: about 16.7 ms per frame at 60 Hz and about 8.3 ms at 120 Hz, and both the UI thread and the raster thread have to fit inside it.
Notes
constmatters for widgets: aconstwidget expression is a single canonical instance, so when its parent rebuilds, the element sees the same object and skips the subtree.conston aTextStyleorEdgeInsetsonly avoids an allocation; it does not skip a rebuild. Enable theprefer_const_constructorslint to catch missed cases.- A widget built with runtime values, such as
FeedCard(title: titles[index]), cannot beconst, so it is rebuilt when its parent rebuilds. Rebuilding is often cheap; the fix for expensive builds is a smaller rebuild scope, not sprinklingconst. ListView.builderbuilds only the items in the viewport plus the cache extent (250 logical pixels by default).ListView(children: [...])creates every child widget up front.ListViewandGridViewalready wrap each item in aRepaintBoundary(addRepaintBoundariesdefaults totrue), so adding your own around list items is redundant.- Use
RepaintBoundaryfor something that repaints often next to something that does not, such as an animated progress indicator in a static card. Each boundary is a separate layer with memory cost, so add it where DevTools shows a benefit. - Turn on Highlight repaints in the DevTools Inspector to see which areas repaint each frame, and the Performance overlay to see UI and raster thread times.
- Shader compilation jank shows up as a raster-thread spike the first time an effect appears. DevTools flags frames that included shader compilation. On the legacy renderer, run with
--purge-persistent-cacheto reproduce a first launch. - Impeller is the default on iOS and on Android API 29+; older Android devices use the legacy renderer. If you support older devices, test animations and blur effects on one of them.
setStatere-runsbuildof thatStateand everything it creates. Keep state close to where it is used, or use Provider, Riverpod, or Bloc selectors so only the widgets that read a value rebuild.- Heavy Dart work (a large JSON parse, image processing) on the main isolate blocks build and layout. Move it to another isolate with
Isolate.runorcompute. Offstagehides a child from painting and hit testing but still lays it out and keeps its animations and tickers running. For hidden tabs,IndexedStackorVisibilitywithmaintainStateare clearer choices.- For Android system-level traces that include the Flutter engine threads, use Perfetto alongside DevTools.
Code example
A feed screen that builds items lazily with ListView.builder, keeps the per-item widget cheap, and uses const where values are fixed at compile time. Each list item already gets its own repaint boundary from ListView.
import 'package:flutter/material.dart';
class FeedScreen extends StatelessWidget {
const FeedScreen({super.key, required this.posts});
final List<Post> posts;
@override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: posts.length,
itemBuilder: (context, index) => FeedCard(post: posts[index]),
);
}
}
class Post {
const Post({required this.id, required this.title, required this.body});
final String id;
final String title;
final String body;
}
class FeedCard extends StatelessWidget {
const FeedCard({super.key, required this.post});
final Post post;
static const _decoration = BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.all(Radius.circular(12)),
boxShadow: [
BoxShadow(color: Color(0x1A000000), blurRadius: 8, offset: Offset(0, 2)),
],
);
@override
Widget build(BuildContext context) {
return Container(
margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
padding: const EdgeInsets.all(12),
decoration: _decoration,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(post.title, style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w600)),
const SizedBox(height: 4),
Text(post.body, style: const TextStyle(fontSize: 14, color: Color(0x88000000))),
],
),
);
}
}ListView.buildercreatesFeedCards only for the visible items plus the cache extent, so the first frame costs about the same for 20 posts or 10 000.const SizedBox(height: 4)is a canonical instance, so the element skips it on rebuild. TheTextwidgets use runtime values, so they are rebuilt; theconston theirTextStyleonly saves an allocation.- The decoration is a
static const, built once and shared by every card. - No manual
RepaintBoundaryis needed:ListViewalready wraps each item in one. - The blurred
BoxShadowis cheap to draw with Impeller. On the legacy renderer the first frame with it may compile a shader, so check that frame in DevTools on an older device.
Run the idea in plain Kotlin
// Models how an element skips a child when the new widget is the
// identical (const) instance it already has.
class Widget(val name: String, val children: List<Widget> = emptyList())
var builds = 0
fun update(old: Widget?, new: Widget, depth: Int) {
val pad = " ".repeat(depth)
if (old === new) {
println(pad + new.name + ": identical instance, skipped")
return
}
builds++
println(pad + new.name + ": rebuilt")
new.children.forEachIndexed { i, child ->
update(old?.children?.getOrNull(i), child, depth + 1)
}
}
// const widgets are canonical: the same object every time.
val constHeader = Widget("Header (const)")
val constFooter = Widget("Footer (const)")
fun buildScreen(counter: Int): Widget = Widget("Screen", listOf(
constHeader,
Widget("Counter " + counter),
Widget("List", listOf(Widget("Item0"), Widget("Item1"))),
constFooter,
))
fun main() {
val first = buildScreen(0)
val second = buildScreen(1) // setState: build runs again
update(first, second, 0)
println("Widgets rebuilt: " + builds)
}Expected output:
Screen: rebuilt
Header (const): identical instance, skipped
Counter 1: rebuilt
List: rebuilt
Item0: rebuilt
Item1: rebuilt
Footer (const): identical instance, skipped
Widgets rebuilt: 5
In production
- Users on low-end Android phones described the home feed as sluggish, although crash rates were normal.
- A profile-mode trace in DevTools showed long UI-thread frames: the build phase alone used most of the frame budget while scrolling.
- The feed used
ListView(children: [...])with every post, and the screen's single top-levelStatecalledsetStateon each "like" tap, rebuilding the whole list.
- The feed switched to
ListView.builder, so only visible items and the cache area are built. - Like state moved into each item's own widget (and later a Riverpod provider per post), so a tap rebuilds one card instead of the whole screen.
- The team re-ran the same scroll in profile mode on the same device and confirmed the UI-thread frames were back inside the budget.
- A new card with a
BackdropFilterblur stuttered the first time it appeared, but only on some older Android phones; newer phones and iPhones were smooth. - The affected phones were below API 29, so they used the legacy renderer, where the blur shader was compiled the first time it was drawn.
- The team had only tested on recent devices, where Impeller had already compiled its shaders at build time.
- An older Android device was added to the test matrix, and the stutter was reproduced in profile mode with
--purge-persistent-cache. DevTools marked the frame as including shader compilation. - Because a backdrop blur is expensive on that hardware even after the first frame, the team showed a plain translucent background instead of the blur on devices below API 29.
- The check is now part of the release checklist: new visual effects are profiled on one Impeller device and one legacy-renderer device.
Common mistakes
- Calling setState at the top of a large screen. Every widget that screen builds is rebuilt. Move state into the smallest widget that needs it, or use Provider, Riverpod, or Bloc so only widgets that read a value rebuild.
- Thinking const on TextStyle or EdgeInsets skips rebuilds. Only a
constwidget lets the framework skip a subtree.constvalues avoid allocations, which helps a little, but the rebuild still happens. - Using ListView(children: [...]) with hundreds of items. Every child widget is created up front. Use
ListView.builderso only visible items plus the cache extent are built. - Adding RepaintBoundary everywhere. Each boundary is a separate layer with memory and compositing cost, and list items already get one. Add it only where Highlight repaints shows a small animation repainting a large area.
- Judging performance in debug mode. Debug mode runs unoptimised JIT code with assertions, so it is slower and less predictable than release. Profile with
flutter run --profileon a real device. - Running heavy work on the main isolate. A large JSON parse blocks build and layout and drops frames. Move it to another isolate with
Isolate.runorcompute.
Interview questions
Answer out loud first. Then reveal the answer and compare it at each depth.
“What happens when you call setState in a StatefulWidget?”
“What is shader compilation jank, and how does Impeller change things?”
“When would you use RepaintBoundary and when would it hurt?”
“Explain the widget, element, and render object trees in Flutter.”
Quiz
What does creating a widget with a const constructor expression let the framework do?
A blurred card stutters the first time it appears on an Android 9 phone but not on newer phones. What is the most likely cause?
A 500-item list takes a long time to show its first frame. What is the most likely fix?
Which renderer does Flutter use by default on an Android API 29+ device?
0 of 4 answered
Mini task
Profile and fix a janky feed screen (15 min)
-
In a Flutter project, build a screen with
ListView(children: [...])of 300 cards, each with aBoxShadow, a title and a body. Keep all screen state (for example a "liked" set) in one top-levelStateand callsetStateon every like tap. -
Run
flutter run --profileon a physical Android device. Open DevTools from the link printed in the terminal, go to the Performance tab, and turn on the Performance overlay (or pressPin the terminal). -
Scroll and tap like a few times. In the frame chart, note whether slow frames are on the UI thread (build and layout) or the raster thread, and which phase takes the time.
-
Fix the build cost: switch to
ListView.builder, move the liked state into each card (or a state holder the card reads), and addconstto fixed widgets such as spacers. Turn on Track widget builds in the Performance tab (or the rebuild stats in your IDE's Flutter Performance view) and check that a like tap rebuilds one card. -
Re-run the same scroll and taps in profile mode and compare the frame chart with your first run.
Done condition: In profile mode, scrolling and liking stay within the frame budget on your device (no red bars in the overlay), and a like tap rebuilds only the tapped card.