17

Is it possible to do inter widget communication via something like a notification/event bus?

I need to be able to tell one widget to react to something that happened in another and didn't want to create a hard link.

The notification listener will only fire is if it is higher in the widget tree than both of the widgets so that isn't probably a viable solution.

Luke
  • 6,388
  • 3
  • 26
  • 35
  • And you've ruled out separating business logic (which manipulates state) from the widgets themselves? Naively, business logic would update the global state (a la redux or similar) which would then cascade through the widget tree? – Seth Ladd Jun 02 '17 at 04:18

1 Answers1

22

There are lots of ways to do this depending on your use case.

You could have them be AnimatedWidgets that are passed a ValueNotifier or ChangeNotifier as the listenable. You can see this pattern in the Gallery's animation example.

You could use StreamBuilder to have your widgets rebuild automatically when new events come in on a Stream. There aren't a lot of examples of this in the main Flutter repo, but it's something that you're likely to need once you start using plugins or doing network I/O.

You could use a GlobalKey to get currentState and have one State call methods on the other. This is how snackbars work (example).

You can also extend InheritedWidget to provide widgets with information that wasn't passed as a constructor argument, and they'll automatically be marked for rebuild when that information changes. This is how Themes work, for example.

If you can provide more details on what your widgets do / what their relationship is, or ideally a code snippet I can help you decide which approach would make the most sense for your situation.

Collin Jackson
  • 110,240
  • 31
  • 221
  • 152
  • what about the BLoC pattern? – Itai Spector Nov 17 '20 at 15:53
  • 1
    More examples (not mine) of using [StreamController + StreamSubscription](https://medium.com/@iamerikchacon/flutter-widget-communication-with-streams-b99dc94c3a5b), and [callback functions](https://www.digitalocean.com/community/tutorials/flutter-widget-communication). – ccpizza Apr 30 '21 at 18:46