Sub topic 11
Keep Build Methods Free of Expensive Work
This chapter assumes you know Dart classes, StatelessWidget and StatefulWidget, and setState. It also assumes you have read how rebuilds are triggered. The earlier chapters narrowed which widgets rebuild. This one makes each build call cheap, because some rebuilds can't be avoided.
Why build must stay cheap
Flutter may call build at any time. A setState call, an inherited widget change, a parent rebuild, an animation tick, or a hot reload can each trigger it. During an animation, build can run on every frame. At 60 Hz the frame budget is about 16 ms for the UI thread and the raster thread combined. At 120 Hz it is about 8 ms. Any work you put in build runs inside that budget.
Treat build as a pure, fast function from state to widgets. It should describe the UI and do nothing else. Three rules follow from that:
buildmust not have side effects.buildmust not do work that scales with data size, unless the framework spreads that cost for you (as lazy lists do).buildmust produce the same result for the same inputs, so skipped or repeated calls are harmless.
What counts as expensive work
Common offenders found in large screens:
- Sorting, filtering, grouping, or mapping a large list on every build.
- Parsing JSON or formatting many dates and numbers.
- Creating objects that hold resources, such as
TextEditingController,AnimationController,ScrollController,Future, orStream. - Starting network, database, or file I/O.
- Building
RegExpobjects,DateFormat, orNumberFormatinstances repeatedly. - Calling
setStateor changing notifiers during build.
The first four are costly in CPU time. The last two groups are costly in correctness: they cause repeated requests, leaked controllers, or errors.
Derived data computed on every build
Here is a typical problem. The screen filters and sorts a list each time it builds, including builds caused by something unrelated like a text field's focus change.
import 'package:flutter/material.dart';
class Product {
const Product(this.id, this.name, this.price);
final int id;
final String name;
final double price;
}
class SlowProductList extends StatefulWidget {
const SlowProductList({super.key, required this.products});
final List<Product> products;
@override
State<SlowProductList> createState() => _SlowProductListState();
}
class _SlowProductListState extends State<SlowProductList> {
String _query = '';
@override
Widget build(BuildContext context) {
// Runs on every build, even when only unrelated state changed.
final visible = widget.products
.where((p) => p.name.toLowerCase().contains(_query.toLowerCase()))
.toList()
..sort((a, b) => a.price.compareTo(b.price));
return Column(
children: [
TextField(onChanged: (v) => setState(() => _query = v)),
Expanded(
child: ListView.builder(
itemCount: visible.length,
itemBuilder: (context, i) =>
ListTile(title: Text(visible[i].name)),
),
),
],
);
}
}For a few dozen items this is fine. For ten thousand it is not, and a sort is O(n log n) work repeated on every keystroke and every unrelated rebuild.
The fix is to recompute only when the inputs change. Inputs here are widget.products and _query. Store the result in a field and update it in the two places where an input can change.
import 'package:flutter/material.dart';
class Product {
const Product(this.id, this.name, this.price);
final int id;
final String name;
final double price;
}
class FastProductList extends StatefulWidget {
const FastProductList({super.key, required this.products});
final List<Product> products;
@override
State<FastProductList> createState() => _FastProductListState();
}
class _FastProductListState extends State<FastProductList> {
String _query = '';
late List<Product> _visible;
@override
void initState() {
super.initState();
_visible = _computeVisible();
}
@override
void didUpdateWidget(covariant FastProductList oldWidget) {
super.didUpdateWidget(oldWidget);
// Recompute only if the incoming list is a different instance.
if (!identical(oldWidget.products, widget.products)) {
_visible = _computeVisible();
}
}
List<Product> _computeVisible() {
final q = _query.toLowerCase();
return widget.products
.where((p) => p.name.toLowerCase().contains(q))
.toList()
..sort((a, b) => a.price.compareTo(b.price));
}
void _onQueryChanged(String value) {
setState(() {
_query = value;
_visible = _computeVisible();
});
}
@override
Widget build(BuildContext context) {
return Column(
children: [
TextField(onChanged: _onQueryChanged),
Expanded(
child: ListView.builder(
itemCount: _visible.length,
itemBuilder: (context, i) =>
ListTile(title: Text(_visible[i].name)),
),
),
],
);
}
}Now build only reads _visible. An unrelated rebuild costs nothing extra.
This pattern has a gotcha. identical checks the list instance, not its contents. If a parent mutates the same list in place and passes it again, didUpdateWidget will not recompute and the screen will show stale data. Treat lists passed into widgets as immutable and create a new list for each change. If you can't guarantee that, compare contents or a version number instead.
Resources created in build
Creating a controller in build creates a new one on each rebuild. The old one is never disposed, and the new one has no state from the old one.
import 'package:flutter/material.dart';
// Bug: a new controller per build loses text and cursor position.
class BrokenField extends StatelessWidget {
const BrokenField({super.key});
@override
Widget build(BuildContext context) {
final controller = TextEditingController();
return TextField(controller: controller);
}
}
// Correct: the State owns the controller for its whole lifetime.
class WorkingField extends StatefulWidget {
const WorkingField({super.key});
@override
State<WorkingField> createState() => _WorkingFieldState();
}
class _WorkingFieldState extends State<WorkingField> {
final TextEditingController _controller = TextEditingController();
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return TextField(controller: _controller);
}
}The same rule applies to AnimationController, ScrollController, FocusNode, and StreamController. Create them in initState (or as a field initializer) and release them in dispose.
Futures and streams created in build
FutureBuilder and StreamBuilder subscribe to whatever object you give them. If you create that object inside build, every rebuild starts a new request.
import 'package:flutter/material.dart';
Future<String> fetchGreeting() async {
await Future<void>.delayed(const Duration(seconds: 1));
return 'Hello';
}
class GreetingScreen extends StatefulWidget {
const GreetingScreen({super.key});
@override
State<GreetingScreen> createState() => _GreetingScreenState();
}
class _GreetingScreenState extends State<GreetingScreen> {
// Created once. A rebuild reuses the same Future.
late final Future<String> _greeting = fetchGreeting();
@override
Widget build(BuildContext context) {
return FutureBuilder<String>(
future: _greeting, // Not fetchGreeting(): that would refetch per build.
builder: (context, snapshot) {
if (snapshot.connectionState != ConnectionState.done) {
return const CircularProgressIndicator();
}
return Text(snapshot.data ?? '');
},
);
}
}If the request depends on a parameter, create a new future in didUpdateWidget when that parameter changes, or when the user triggers a refresh.
Caching expensive objects
Some objects are expensive to construct and safe to reuse. DateFormat from package:intl and RegExp are common examples. Make them static final or top-level final so they are created once.
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
class PriceLabel extends StatelessWidget {
const PriceLabel({super.key, required this.amount});
final double amount;
// Created once for the whole app, not once per build.
static final NumberFormat _format = NumberFormat.currency(symbol: r'$');
@override
Widget build(BuildContext context) {
return Text(_format.format(amount));
}
}A static formatter does not follow locale changes. If your app lets users switch locale at runtime, build the formatter from Localizations.localeOf(context) and cache it in State, rebuilding it in didChangeDependencies.
Heavy computation: move it off the UI thread
Sometimes the work can't be avoided, such as decoding a large JSON payload or processing an image. Caching helps with repeats, but the first run still blocks the UI thread. Run it in a background isolate with compute (or Isolate.run), and show the result with a FutureBuilder, as above.
import 'dart:convert';
import 'package:flutter/foundation.dart';
List<Object?> _parse(String body) => jsonDecode(body) as List<Object?>;
Future<List<Object?>> parseInBackground(String body) {
return compute(_parse, body);
}The function passed to compute must be a top-level or static function. Data is copied between isolates, so passing very large objects has its own cost. Moving work off-thread is not worth it for small inputs, because the setup cost can exceed the work.
Cheap rebuilds that are fine to leave alone
Not every rebuild needs fixing. A build that creates a few Text, Padding, and Row widgets is cheap. Widget objects are lightweight, and Flutter's element tree compares them against existing elements rather than rebuilding everything below. Optimize when measurement shows a problem.
| Work in build | Typical cost | Action |
|---|---|---|
| Creating widgets and `TextStyle` values | Very low | Leave alone |
| `Theme.of(context)`, `MediaQuery.sizeOf(context)` lookups | Low | Leave alone |
| `where`/`map` over a short list | Low | Leave alone |
| Sort or filter over thousands of items | High | Cache in state |
| Creating a controller, future, or stream | Leaks or repeats work | Move to `initState` |
| JSON decode, image processing | Very high | Use an isolate |
Checking your change
Use the tools from the measurement chapter in profile mode. Open DevTools, record a performance timeline, and look at the UI thread's frame times for the interaction in question. A build that was slow shows up as a long "Build" phase in the frame. After your change, repeat the same interaction and compare. If the number didn't move, the work you removed was not the bottleneck, and you should revert it to keep the code simple.
Exercise
A screen's build method calls final sorted = [...items]..sort(compare); and the screen also has a TextField that calls setState on every keystroke to update a search box hint. Sorting 20,000 items makes typing laggy. Where should the sort go, and what must you handle so the list stays correct?
Show answer
Move the sort into a field (for example late List<Item> _sorted) that is computed in initState and recomputed in didUpdateWidget when widget.items changes (or in the handler that changes the sort order). build then only reads _sorted, so keystroke rebuilds don't re-sort. You must handle every input that affects the result: a new items list from the parent, and any change to the comparison. Also treat the incoming list as immutable, because an identical check misses in-place mutation.
Exercise
Why does FutureBuilder(future: fetchData(), ...) inside build cause repeated network requests, and how do you fix it?
Show answer
Each call to build runs fetchData() again and produces a new Future, so FutureBuilder sees a different future and restarts. Store the future in a State field created in initState (or a late final field), and pass that field to FutureBuilder. Create a new future in didUpdateWidget or on refresh only when its input changes.