alexeieleusis / greencat

A port of Redux(https://github.com/reactjs/redux) to Dart, including Redux Thunk(https://github.com/gaearon/redux-thunk) and a simple Logger.
Apache License 2.0
48 stars 4 forks source link

Reuse Store #13

Closed theobouwman closed 7 years ago

theobouwman commented 7 years ago

Hello,

how can I reuse a Store in multiple widgets?

alexeieleusis commented 7 years ago

I am not sure I understand the question, and I will defer to @yjbanov to provide advice for flutter.

The short answer is that you keep a reference to it and pass it to the interested consumers, but that is not always feasible.

In Angular you would need to provide it at some level in the providers section of the @Component annotation docs. I will update the examples to include injection.

theobouwman commented 7 years ago

Well, right now I use a singleton to keep only one instance of the store. And I dontt know if that is a good solution.

alexeieleusis commented 7 years ago

Usually you only want one store instance per app, even if it is a composed one. Patterns are about easing communication between developers in a team and having a sustainable development environment.

I particularly think that enforcing that need is too much, having the store provided at the app level should be enough, YMMV. That said there were a couple of bugs in the dart analyzer or DDC that didn't recognize some of generic types used in a store, though most likely those bugs are fixed in the last SDK version.

theobouwman commented 7 years ago

having the store provided at the app level should be enough Why is that enough? How can I access it in lowerlevel components/ other screens?

alexeieleusis commented 7 years ago

You retrieve/provide it via dependency injection. That also eases testing, which inevitably requires trickery when using singletons.

yjbanov commented 7 years ago

The current idiomatic way to do DI-like things in Flutter is via InheritedWidget. For example, using it we "inject" theme, medial query and other things down the widget tree. It supports scoping, i.e. you can inject different instances of the same class to different branches of the UI tree.

theobouwman commented 7 years ago

@yjbanov do you have an example of this?

Sent from my Google Nexus 5X using FastHub

yjbanov commented 7 years ago

TickerProvider is one of the simplest examples. It allows turning animations on/off in UI subtrees as needed. It publishes itself as an InheritedWidget and provides an of() method to look up its value in the UI hierarchy.