Chapter 2 of 8 · 5 practices · 3 min · 4-question quiz
Widgets and build methods
How to shape widgets so Flutter can rebuild only what changed. Cheap build methods and well-placed state are the base of every smooth Flutter app.
Start: Keep build() free of costly and repeated work5 practices in this chapter
- 1Keep
build()free of costly and repeated workThe Flutter docs say to avoid repetitive and costly work inbuild()methods, sincebuild()can be called frequently when ancestor widgets rebuild. A parent animation, a theme change or a keyboard… - 2Split large widgets by how they change, and call
setState()low in the treeA single 400-line widget that callssetState()rebuilds everything inside it, even parts that never change. The Flutter docs recommend splitting large widgets based on encapsulation but also on how… - 3Use
constconstructors wherever you canThe Flutter docs say to useconstconstructors on widgets as much as possible, since they allow Flutter to short-circuit most of the rebuild work. Aconstwidget is created once at compile time… - 4Prefer a
StatelessWidgetover a helper function that returns widgetsIt is tempting to breakbuild()into methods like_buildHeader(). The Flutter docs recommend the opposite: to create reusable pieces of UI, prefer aStatelessWidgetrather than a function. - 5Dispose every controller, subscription and focus node you createControllers such as
TextEditingController,AnimationController,ScrollControllerandFocusNode, plusStreamSubscriptions, hold resources and listeners. If aStatecreates one, that…
Check yourself on this chapter
4 questions, right here once you are signed in. Your progress is saved as you read.