Reputation: 7128
How does Flutter rebuild/repaint work in case of:
Does a Stateless widget inside a Stateful widget render each time the Stateful widget State changes?
Can a Stateful widget change inside a Stateless widget? How does it affect the Stateless widget?
Upvotes: 12
Views: 6911
Reputation: 1979
First here is the difference between stateless and stateful from the flutter documentation
A stateless widget never changes. Icon, IconButton, and Text are examples of stateless widgets. Stateless widgets subclass StatelessWidget.
A stateful widget is dynamic: for example, it can change its appearance in response to events triggered by user interactions or when it receives data.
For the first scenario "Creating a Stateless widget inside a Stateful widget."
when we update the state of the Stateful widget it will re-run its build function, when a stateless widget is part of that build function, flutter will check if its input data has changed or not, if not it will return the same instance of the widget, if it's changed then it will create another instance from the stateless widget and discard the previous one.
here is an illustration of the above scenario from this article
For the second scenario "Creating a Stateful widget inside a Stateless widget."
let's try to illustrate the widget tree first to visualize what's going on.
Stateless (1)
/ \
/ \
(2) Stateful Stateless (3)
if we update the state of the stateful widget (2), both (1) and (3) won't get affected, but our build function in the stateful widget will be called again.
and if the input coming for the parent (1) changes, then (1) and (2) will be rebuilt again and flutter will check if (3) has input data changes it will be also rebuilt, if not it will return the same instance.
hope this answers your question and makes you better understand how flutter renders its UI
Note: this is my current understanding of the way flutter handles rebuilding stateful and stateless widgets, feel free to correct me if anything is not correct.
Upvotes: 31