Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inter Widget communication

Tags:

flutter

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.

like image 815
Luke Avatar asked Jun 01 '17 13:06

Luke


People also ask

How do widgets communicate with each other?

Widgets can communicate with each other in two ways: Communication Through Events. Communication Through URL.


1 Answers

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.

like image 192
Collin Jackson Avatar answered Sep 17 '22 00:09

Collin Jackson