Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Notify parent widget from sub children widgets

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

like image 601
Utkarsh Sharma Avatar asked Oct 23 '25 08:10

Utkarsh Sharma


1 Answers

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,
    );
  }
}
  • use 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);
      },
    );
  }
}
like image 195
Rémi Rousselet Avatar answered Oct 24 '25 23:10

Rémi Rousselet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!