Utkarsh Sharma
Utkarsh Sharma

Reputation: 43

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

Upvotes: 3

Views: 2105

Answers (2)

Rémi Rousselet
Rémi Rousselet

Reputation: 276957

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);
      },
    );
  }
}

Upvotes: 4

Rodrigo Bastos
Rodrigo Bastos

Reputation: 2448

Why do you want to refresh? You updated any data and wanted the new ones to be displayed?

You could try to use Provider widget. With it you can modify any data and notify everyone interested in that data that it changed.

In your setup you could put the provider on the A widget, on the C widget you could get the value, updated and notify everyone. When doing that, A widget will automatically rebuild with the updated information.

The code would be something like this:

class AppState with ChangeNotifier {
  AppState();

  YourData _data;

  void setData(YourData data) {
    _data = data;
    notifyListeners();
  }
}

ChangeNotifierProvider.value(
  value: AppState(),
  child: WidgetA()
)

WidgetC() {
  Provider.of<AppState>(context).setData(yourChangedDataHere);
}

Upvotes: 0

Related Questions