Home > Software design >  How to pass data child to child widget without rebuild parent widget in flutter?
How to pass data child to child widget without rebuild parent widget in flutter?

Time:06-13

I have one ParentWidget having two child widget. I want to pass some callback action from FirstChild() to SecondChild() Widget without rebuild ParentWidget()like setState((){}).

I want to do because ParentWidget() has many widget. And this callback action continuously happen.

And continuously setState((){}) is not viable option for ParentWidget()

For example

setState((){}) call from FirstChild() than I want to rebuild SecondChild() without rebuild ParentWidget()

CodePudding user response:

StatefulWidget is only useful in very simple business logic cases. I highly recommend that you have a look at Riverpod, where you can access a "state" from any widget, regardless of who its parent widget is. And because of how Riverpod is designed, it will not trigger any unnecessary rebuilds.

Sticking with StatefulWidget, you will need to use something like InheritedWidget as a parent of both widgets, and then have them both access it.

CodePudding user response:

You can get help with state management solutions like Provider or Riverpod. I may write an example code if you use Riverpod, but generally speaking, in such case, you need to place the state outside the Parent widget into some external variable. Then you can access and share it between both Children without rebuilding Parent.

  • Related