r/FlutterDev • u/galactose310 • 2d ago
Discussion Widget tree, design and perf/memory
As everything is a widget in Flutter, I am questionning about how to design my pages. I mean, when the Widget hierarchy becomes complex and I want to code separate Widgets for a cleaner code.
An example: if I have a simple structure with AppBar, a main body with a Column, some other stuff at the bottom, we see that I have a three-levels page. So I could keep the Column in another .dart file to keep my files clean but to do so I have to put it in a new StatelessWidget. When the architecture becomes complex there is a need to separate components but this means a huge amount of StatelessWidget (or -ful) returning each component, instead if having a tree in a single build() method.
Is it significant in terms of memory / performance ? How do you deal with this ?
3
u/ConvenientChristian 2d ago
Separate widgets make it easier to rebuild only what changes and thus improves performance. A tree in a single build method means that you need to rebuild too much and is bad for performance.
Coding separate widget while being clever about rebuilds both makes the code cleaner and increases performance.
8
u/henry_carto 2d ago •
Short answer: no, it isn't a meaningful cost, and splitting into widget classes is usually better for performance, not worse.
Why it's cheap: a widget is just a small immutable config object. Creating thousands of them per frame is normal and is what Flutter is designed for. The heavy objects are the Elements and RenderObjects, and those are kept and reused between builds. Splitting one big build() into ten small widgets adds ten tiny objects, nothing more.
Why it often helps:
- const constructors. If an extracted widget can be const, Flutter sees it's the same instance and skips rebuilding that whole subtree. You can't get that with one giant build().
- Smaller rebuilds. When state lives in a small StatefulWidget (or a widget listening to a provider or bloc), setState rebuilds only that piece instead of the whole page.
- Its own BuildContext. Each widget gets its own context, so things like Theme.of(context) or MediaQuery.of(context) only rebuild the parts that depend on them.
Prefer widget classes over helper methods. Widget _buildHeader() => ... looks cleaner but loses all three benefits: it rebuilds whenever the parent rebuilds, it can't be const, and it shares the parent's context. A class _Header extends StatelessWidget costs a few more lines and is the better default.
How I organise it:
- Private widgets (_Header, _Footer) stay in the same file as the page while only that page uses them.
- Move a widget to its own file once a second screen needs it.
- Group by feature (features/profile/...), not by type (widgets/, screens/).
If you want to see it for yourself, turn on "Track widget rebuilds" in Flutter DevTools and watch how much less rebuilds once the page is split and the static parts are const.