3

I am using the following code in my Dart which uses redux and flutter_redux packages. Everything works fine but as you can see I have to use the following syntax to call the appropriate action.

callback['onIncrement'](34) 

It works but it is ugly. How can I improve it so it reads more like this:

callback.onIncrement(34)

Here is the code:

StoreConnector<AppState,Map<String,Function>>(
    converter: (store) {
      return {
        'onIncrement': (value) => store.dispatch(IncrementAction(value)), 
        'onDecrement': () => store.dispatch(Actions.decrement)
      };
    },
    builder: (context, callback) {
      return Column(
        children: <Widget>[
          FlatButton(
          child: Text('Increment Counter', style: TextStyle(color: Colors.white)),
          color: Colors.orange, 
          onPressed: () => callback['onIncrement'](1)

UPDATE:

Now, I am using enums and it is little better:

StoreConnector<AppState,Map<Actions,Function>>(
        converter: (store) {
          return {
            Actions.increment: (value) => store.dispatch(IncrementAction(value)), 
            Actions.decrement: () => store.dispatch(Actions.decrement)
          };
        },
        builder: (context, callback) {
          return Column(
            children: <Widget>[
              FlatButton(
              child: Text('Increment Counter', style: TextStyle(color: Colors.white)),
              color: Colors.orange, 
              onPressed: () => callback[Actions.increment](23)

1 Answer 1

3

As far as I'm concerned, it's not possible to do this in Dart. You should work with ViewModel instead:

StoreConnector<AppState, ViewModel>(
  converter: ViewModel.fromStore,
  builder: (context, viewModel) {
    return FlatButton( 
      onPressed: () => viewModel.onIncrement(1),
      ...
    );
  },
}

...

class ViewModel {
  final void Function(int) onIncrement;
  final void Function(int) onDecrement;

  ViewModel({@required this.onIncrement, @required this.onDecrement});

  factory ViewModel.fromStore(Store store) {
    return ViewModel(
      onIncrement: (value) => store.dispatch(IncrementAction(value)),
      onDecrement: (value) => store.dispatch(DecrementAction(value)),
    );
  }
}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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