Chapter 2 · Practice 2 of 5
Split large widgets by how they change, and call setState() low in the tree
Why it matters
A single 400-line widget that calls setState() rebuilds everything inside it, even parts that never change. The Flutter docs recommend splitting large widgets based on encapsulation but also on how they change, and keeping the setState() call in the part of the subtree whose UI actually needs to change.
A practical way to do it:
- Find the piece of state that changes often, such as a counter, a toggle or a text field value.
- Move that state and the widgets that show it into their own
StatefulWidget. - Leave the static parts of the screen in the parent, ideally as
constwidgets.
Now a tap rebuilds a small subtree instead of the whole screen.
Do
- Give frequently changing state its own small widget
- Keep static headers, images and layout in the parent
Avoid
- Calling
setState()at the top of a screen to update one icon