brianegan / flutter_redux

A library that connects Widgets to a Redux Store
MIT License
1.65k stars 217 forks source link

Possibility to create a ViewModel with a custom argument #156

Closed sturmf closed 5 years ago

sturmf commented 5 years ago

I am looking for a way to pass a custom id to the ViewModel that is created by the StoreConnector. What I am currently doing is the following:

Widget build(BuildContext context) {
  return StoreConnector(
    converter: _ViewModel.fromStore,
    builder: (context, vm) {
  ...

Now e.g. think about a TodoList app and I am navigating to a specific todo item. The id of the item can be passed as argument in the named route. But I now have to forward this id to the ViewModel since I want it to expose only the single todo item that got selected. How would I do this?

I tried something like this but I might misunderstand Dart here

Widget build(BuildContext context) {
  return StoreConnector(
    converter: (store) {
      return _ViewModel.fromStore(store, id);
    },
    builder: (context, vm) {
  ...
miquelbeltran commented 5 years ago

Yes, that's possible.

What you have to do is to return a function that takes a Store, for example:

static MyViewModel Function(Store<AppState> store) fromStore(String id) {
    return (Store<AppState> store) {
         ... create and return your ViewModel here, you can use the `id`
   }
}

And you use it like this:

Widget build(BuildContext context) {
  return StoreConnector(
    converter: _ViewModel.fromStore(id),
    builder: (context, vm) {
  ...

You can see a working example of that in this project: https://github.com/janoodleFTW/timy-messenger/blob/64d39ac266e7e76fad46709275319e85d4900582/lib/presentation/channel/invite/invite_to_channel_screen.dart#L25

sturmf commented 5 years ago

Thanks, worked like a charm!