Suppose i have widget tree like this.
Widget1(
void someEvent(){
if(true){
}
}
child: Widget2(
child: Widget3(
child: Widget4(
void someFunction(){
//called when event occurs in Widget1
}
child:Container()
),
),
),
)
Suppose if some events occurs in Widget1
and if some condition is true then in Widget4
i should call a function automatically.
The someEvent
function can be called many times and if condition is true then
the Widget4
should call its custom function that many times.
How can i achieve the requirements which i mentioned?
2
Answers
You can use
InheritedWidget
whenever the parent widget of
MyInheritedData
is built, (Widget1)MyInheritedData.updateShouldNotify
is triggered and if it returns true,then all descendants (Widget4) will trigger their
didChangeDependencies
.Edit
InheritedWidget
is built in flutter. you can use a state management package if you want to write less code. here is an example using riverpod:You can achieve this by using a callback function.
Widget1
has a callback functiononSomeEvent
that is passed toWidget4
through the widget tree. WhensomeEvent
is called inWidget1
, it calls theonSomeEvent
callback function, which is then executed inWidget4
.You can also use a state management solution like
Provider
.