skip to Main Content

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


  1. 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

    Login or Signup to reply.
  2. You cannot control whether or not a widget is being rebuilt. This can happen in many situations you don’t have control over:

    • The screen size changes
    • Some dependencies changed (ex: theme)
    • A parent rebuilds multiple times (for example because of an animation)
    • etc

    Checkout this answer from RĂ©mi Rousselet

    The build method is designed in such a way that it should be pure/without side effects.

    The problem you are facing is that your build method has side effects/is not pure, making extraneous build calls troublesome.

    Instead of preventing build calls, you should make your build method pure, so that it can be called anytime without impact.

    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, or didUpdateWidget, and store, for example, an API call in the state.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search