在Dart和Flutter中具有强类型属性的匿名对象

时间:2019-05-20 17:33:23

标签: dart flutter

我在Dart中使用以下代码,该代码使用redux和flutter_redux软件包。一切正常,但是如您所见,我必须使用以下语法来调用适当的操作。

callback['onIncrement'](34) 

它可以工作,但是很难看。我该如何改善它,使其读起来像这样:

callback.onIncrement(34)

这是代码:

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)

更新:

现在,我正在使用枚举,它好一点了:

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 个答案:

答案 0 :(得分:2)

就我而言,在Dart中无法做到这一点。您应该改为使用ViewModel

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

...

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

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

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