Flutter Best Practices

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 work

5 practices in this chapter

  1. 1Keep build() free of costly and repeated workThe Flutter docs say to avoid repetitive and costly work in build() methods, since build() can be called frequently when ancestor widgets rebuild. A parent animation, a theme change or a keyboard…
  2. 2Split large widgets by how they change, and call setState() low in the treeA 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…
  3. 3Use const constructors wherever you canThe Flutter docs say to use const constructors on widgets as much as possible, since they allow Flutter to short-circuit most of the rebuild work. A const widget is created once at compile time…
  4. 4Prefer a StatelessWidget over a helper function that returns widgetsIt is tempting to break build() into methods like _buildHeader(). The Flutter docs recommend the opposite: to create reusable pieces of UI, prefer a StatelessWidget rather than a function.
  5. 5Dispose every controller, subscription and focus node you createControllers such as TextEditingController, AnimationController, ScrollController and FocusNode, plus StreamSubscriptions, hold resources and listeners. If a State creates one, that…

Check yourself on this chapter

4 questions, right here once you are signed in. Your progress is saved as you read.

Sign up for the quiz