I am trying to refresh the parent widget from sub children widget. Actually, there are a number of widgets in between like A uses B and B uses C. I would like to refresh A widget on an event in C widget.I researched a lot but couldn't find an exact answer. A code snipped will be really helpful. Thanks in advance
There are a few solutions:
A pass a callback that does a setState to B, which then pass it to C:class A extends StatefulWidget {
@override
_AState createState() => _AState();
}
class _AState extends State<A> {
@override
Widget build(BuildContext context) {
return B(
onSomething: () => setState(() {}),
);
}
}
class B extends StatelessWidget {
final VoidCallback onSomething;
const B({Key key, this.onSomething}) : super(key: key);
@override
Widget build(BuildContext context) {
return C(onSomething: onSomething);
}
}
class C extends StatelessWidget {
final VoidCallback onSomething;
const C({Key key, this.onSomething}) : super(key: key);
@override
Widget build(BuildContext context) {
return RaisedButton(
onPressed: onSomething,
);
}
}
NotificationListener in A, and dispatch a Notification from C:class MyNotification extends Notification {}
class A extends StatefulWidget {
@override
_AState createState() => _AState();
}
class _AState extends State<A> {
@override
Widget build(BuildContext context) {
return NotificationListener<MyNotification>(
onNotification: (_) {
setState(() {});
},
child: B(),
);
}
}
class C extends StatelessWidget {
@override
Widget build(BuildContext context) {
return RaisedButton(
onPressed: () {
MyNotification().dispatch(context);
},
);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With