Sub topic 2
How Flutter Rebuilds UI from State
Prerequisites and the rebuild model
Assume you know Dart async and await, Flutter widgets, StatefulWidget, setState, initState, and dispose. This chapter focuses on the rebuild process that makes asynchronous UI possible.
Flutter uses a declarative UI model. You describe what the interface should look like for the current state. Flutter calls build to create that description, then updates the rendered interface when the state changes.
A widget's build method is not a one-time constructor. Flutter may call it many times. It can rebuild because:
- The widget's own state changed.
- A parent widget rebuilt and supplied new inputs.
- An inherited value, such as a theme or media query, changed.
- A framework event caused a dependent widget to update.
A rebuild should therefore be fast and free of side effects. It should calculate widgets from current values, not start network requests, open controllers, or modify state.
import 'package:flutter/material.dart';
class CounterPanel extends StatefulWidget {
const CounterPanel({super.key});
@override
State<CounterPanel> createState() => _CounterPanelState();
}
class _CounterPanelState extends State<CounterPanel> {
int _count = 0;
void _increment() {
setState(() {
_count++;
});
}
@override
Widget build(BuildContext context) {
return Column(
mainAxisSize: MainAxisSize.min,
children: [
Text('Count: $_count'),
ElevatedButton(
onPressed: _increment,
child: const Text('Increment'),
),
],
);
}
}When the button runs _increment, setState tells Flutter that this State object has new information. Flutter schedules a rebuild. The build method then reads the new value of _count and returns a new widget description.
setState does not directly change pixels. It marks the state as dirty so Flutter can run the normal build, layout, and paint pipeline.
State belongs outside `build`
The State object persists across rebuilds while the widget remains in the tree. Fields on that object can hold values that must survive from one build to the next.
This distinction matters for asynchronous work. A Future represents a computation that eventually produces one result or an error. A Stream represents a sequence of values delivered over time. Both computations often outlive one call to build.
The following diagram shows the relationship between state changes and rebuilding:
Store long-lived objects in the appropriate lifecycle method or field initializer. Create them in initState when initialization depends on the State object, and release resources in dispose.
How this affects async widgets
Suppose a screen needs a user name from a server. If the request is started inside build, every rebuild can create another request. A parent rebuild, orientation change, or theme change might restart the operation even though the user did nothing.
Instead, create the Future once and store it in state:
class UserScreen extends StatefulWidget {
const UserScreen({super.key});
@override
State<UserScreen> createState() => _UserScreenState();
}
class _UserScreenState extends State<UserScreen> {
late final Future<String> _name;
@override
void initState() {
super.initState();
_name = _loadName();
}
Future<String> _loadName() async {
return 'Ada';
}
@override
Widget build(BuildContext context) {
return Text('Request ready: $_name');
}
}In practice, a FutureBuilder consumes _name and chooses widgets for loading, error, or success. The important boundary is already visible: initState starts the operation once, while build only describes the current interface.
A stream follows the same principle. Keep the stream or its controller stable, subscribe through StreamBuilder, and close an owned StreamController in dispose.
Common rebuild mistakes
| Mistake | Result | Better approach |
|---|---|---|
| Starting a `Future` inside `build` | The work may restart on every rebuild | Store the `Future` in state |
| Changing a field without `setState` | The UI may not update | Change it inside `setState` |
| Creating a controller in `build` | Multiple controllers and resource leaks | Create it once and close it |
| Doing expensive synchronous work in `build` | Janky frames | Move work elsewhere and render its result |
Exercise
Why should an asynchronous request usually not be started directly inside build?
Show answer
Flutter can call build many times, so the request could restart repeatedly. Create the operation once in initState or in response to an explicit action, then let build render its current result.