What is the relation between stateful and stateless widgets in Flutter?
A stateful widget is defined as any widget which changes its state within its lifetime. But it is a very common practice for a StatelessWidget
to have a StatefulWidget
as one of its children. Doesn't StatelessWidget
become stateful if it has StatefulWidget
as one of its children?
I tried looking into the documentation as part of the code of StatelessWidget
, but couldn't figure out how a StatelessWidget
can have Statefulwidget
as its children and still remain StatelessWidget
.
What is the relation and difference between stateful and stateless widgets in Flutter?
A StatelessWidget will never rebuild by itself (but can from external events). A StatefulWidget can. That is the golden rule.
BUT any kind of widget can be repainted any times.
Stateless only means that all of its properties are immutable and that the only way to change them is to create a new instance of that widget. It doesn't e.g. lock the widget tree.
But you shouldn't care about what's the type of your children. It doesn't have any impact on you.
From the documentation at flutter.io:
...The important thing to note here is at the core both Stateless and Stateful widgets behave the same. They rebuild every frame, the difference is the StatefulWidget has a State object which stores state data across frames and restores it.
If you are in doubt, then always remember this rule: If a widget changes (the user interacts with it, for example) it’s stateful. However, if a child is reacting to change, the containing parent can still be a Stateless widget if the parent doesn’t react to change.