1

I'm discovering Flutter and I really love it. I'm building a simple app where I have few instances of Statefull custom widget "Counter" on a Scafold's body, and I have a "Reset" button on the drawer.

What's the best way to call a "resetCounter" method on all "Counter" instances when tap on the "Reset" button ?

I've managed the other way (calling a callback method of a parent from a child), but I can't find the other way. The only solution I've found is by using GlobalKeys, but it doesn't seems appropriate.

Thanks

Nicolas Youpi
  • 178
  • 3
  • 11

2 Answers2

3

Indeed for your case callback function might be the right one. But when your app will grow the widget hierarchy will become more and more complex. For now you have Parent —> Child relationship and it’s quite easy to pass callback function, but when you’ll get Parent —> Widget A—> Widget B—> Child situation in order to pass callback from Parent to Child you’ll need to pass it through Widget A and Widget B as well.

For me, your problem sounds like a perfect candidate for reactive streams. You may create a Sink which will be used when user tap on Reset button and your Counter will observe this event and handle it with resetCounter method. You may learn more about reactive programming (and other ways to solve your problem) from this presentation.

olexa.le
  • 1,697
  • 10
  • 14
0

There is another approach to extend ChangeNotifier, and add child as listeners. Once parent perform an action, you can call notifyChange to trigger child widgets callbacks.

Panda World
  • 1,704
  • 1
  • 20
  • 28