Chapter 2 · Practice 4 of 5
Prefer a StatelessWidget over a helper function that returns widgets
Why it matters
It 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.
A widget class gets things a function does not:
- its own
BuildContext, soTheme.ofandMediaQuerylookups are scoped correctly, - the ability to be
constand skipped on rebuild, - its own entry in the widget inspector, which makes debugging easier.
A small private method for a trivial bit of layout is fine. Once it has parameters, conditions or its own look, make it a widget.
Do
- Turn any reused or parameterized
_buildX()method into a widget class
Avoid
- Large
_buildSomething()methods that read context from the parent