0

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

  • Use stage-management solution provider/bloc etc. Otherwise, it'll be hard for you. Or you can try ValueListenableBuilder. – Ashikul Islam Sawan Sep 01 '23 at 22:41
  • Am using the [card_swiper](https://pub.dev/packages/card_swiper) library which results in frequent rebuilds even with slight gestures. – Crypted420 Sep 02 '23 at 05:54

2 Answers2

0

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

0

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.

Valentin Vignal
  • 6,151
  • 2
  • 33
  • 73
  • The issue am trying to solve is from this library [card_swiper](https://pub.dev/packages/card_swiper), It rebuilds very often and I have several children in it who all have individual states which are lost when the library rebuilds – Crypted420 Sep 02 '23 at 05:56