I’m working on a Flutter project and facing an issue related to widget rebuilds. I have a parent widget and a child widget. When the parent widget rebuilds due to state changes, the child widget also rebuilds, which I want to avoid.
Both parent and child are statefulwidgets
I tried adding key values but that did not work
2
Answers
if you are using the setstate it is a normal behavior that refreshes the entire widget tree, what you could do and would be the best option is to use a state manager such as bloc, with which you have greater control of the state of each widget and thus prevent the children from being rebuilt when updating the state of the parent
You cannot control whether or not a widget is being rebuilt. This can happen in many situations you don’t have control over:
Checkout this answer from RĂ©mi Rousselet
So if an extra build brings issues in your stateful widget, it means the build method is not pure and needs to be made pure.
You can use
initState
,didChangeDependencies
, ordidUpdateWidget
, and store, for example, an API call in the state.