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.

1
  • 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
    Commented Jun 2, 2017 at 4:18

1 Answer 1

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.

2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.