flutter_built_redux icon indicating copy to clipboard operation
flutter_built_redux copied to clipboard

Question: dispatching action on widget initialization

Open maxlapides opened this issue 5 years ago • 4 comments

I'd like to dispatch an action when a widget initializes. Normally, I'd put this kind of logic inside initState on a stateful Flutter widget. But, AFAIK, no such feature exists for widgets that extend StoreConnector.

The reason I'd like to do this is so I can do things like make API calls when a widget is initialized. The parallel in the React world would be calling fetch inside of componentDidMount. I think an argument could be made that a better architecture in many cases would be to put the API calls in some middleware that is triggered by a change route action, and this is probably what I'll end up doing. But, I was really interested to hear what the best practice here is. Thanks!

maxlapides avatar Sep 24 '18 20:09 maxlapides

Please give us initState for living!

tdesc avatar Oct 15 '18 16:10 tdesc

The more I think about it, the more I think initState would be an excellent feature for this library, but I'm not sure what the right way to implement it is. @davidmarne if you can point me in the right direction, I would be happy to work on a PR if you agree?

maxlapides avatar Oct 18 '18 20:10 maxlapides

My solution to this has been to create a child stateful widget in between my StoreConnection and the widget that I would normally pass straight to builder:.

I can then override initState on that widget which gives me a place to dispatch my action. It's a bit tediously boilerplate, but it works.

Will-W avatar Dec 11 '18 12:12 Will-W

@smiLLe has a great PR (38) which solves these issues by including these really useful callbacks onInit, onFirstBuild, onDidChange, onDispose which are present in the original flutter_redux package. For me these are pretty much essential, and not sure why they're not merged into main yet.

jamesncl avatar Jun 04 '20 10:06 jamesncl