Sub topic 11
Keep build methods free of expensive work
This chapter assumes that you know basic Dart, StatelessWidget, StatefulWidget, setState, and the build method. You will learn how to keep build fast when a large screen rebuilds often.
Why work in `build` is repeated
Flutter may call build whenever an element becomes dirty. A call can happen after setState, an inherited dependency changes, or a parent supplies new widget data. The framework expects build to describe the current UI quickly. It is not a good place for work that takes noticeable time.
Common examples of expensive work include:
- Filtering or sorting a large collection.
- Decoding JSON or parsing a document.
- Formatting thousands of values.
- Reading a file or making a network request.
- Creating a large object graph.
- Starting a new
Futureor subscription.
An expensive operation in build runs again whenever that widget rebuilds, even when the operation's input has not changed.
The following flow shows the difference between preparing data when its input changes and preparing it during every build.
Move derived work to the event that changes its input
If a text query controls a list, filter the list when the query changes. Store the result in state, then let build display that result.
import 'package:flutter/material.dart';
void main() {
runApp(const MaterialApp(home: SearchPage()));
}
class SearchPage extends StatefulWidget {
const SearchPage({super.key});
@override
State<SearchPage> createState() => _SearchPageState();
}
class _SearchPageState extends State<SearchPage> {
final List<String> _allItems = List<String>.generate(
10000,
(index) => 'Product $index',
);
List<String> _visibleItems = <String>[];
@override
void initState() {
super.initState();
_visibleItems = _filter('');
}
List<String> _filter(String query) {
final normalizedQuery = query.trim().toLowerCase();
return _allItems
.where((item) => item.toLowerCase().contains(normalizedQuery))
.toList();
}
void _updateQuery(String query) {
setState(() {
_visibleItems = _filter(query);
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Products')),
body: Column(
children: [
Padding(
padding: const EdgeInsets.all(16),
child: TextField(
onChanged: _updateQuery,
decoration: const InputDecoration(
labelText: 'Search',
border: OutlineInputBorder(),
),
),
),
Expanded(
child: ListView.builder(
itemCount: _visibleItems.length,
itemBuilder: (context, index) {
return ListTile(title: Text(_visibleItems[index]));
},
),
),
],
),
);
}
}Here, build reads _visibleItems and creates visible widgets. It does not scan all 10,000 products. The scan runs only when the query changes.
This approach also makes the data flow easier to test. You can test _filter separately from the widget tree.
Cache asynchronous work
Do not create a future directly in build:
FutureBuilder<User>(
future: loadUser(),
builder: (context, snapshot) {
return Text(snapshot.data?.name ?? 'Loading');
},
)A rebuild can call loadUser() again and start another request. Instead, create the future once, usually in initState, or store it when the request is intentionally refreshed.
late final Future<User> _userFuture;
@override
void initState() {
super.initState();
_userFuture = loadUser();
}The FutureBuilder can then use _userFuture without recreating the request.
Decide whether optimization is needed
Not every calculation belongs in state. A small expression such as price * quantity is usually cheap enough in build. Move work out only when measurement or clear reasoning shows that it can affect frame time.
| Work | Usual choice |
|---|---|
| Formatting one short label | Keep in `build` |
| Filtering thousands of records | Prepare when input changes |
| Network request | Start outside `build` |
| Creating 10,000 widgets | Use a lazy list |
If preparation itself blocks the UI thread, moving it out of build may not be enough. Consider reducing the data, caching results, or using an isolate for CPU-heavy work.
Exercise
Why can creating a future inside build cause repeated network requests?
Show answer
Flutter can call build many times, so each call can create a new future and start another request. Store the future outside build, such as in initState, when the request should run once.