使用Flutter和Redux(flutter_redux)如何从应用程序状态中取消窗口小部件?

时间:2018-04-03 03:11:28

标签: redux widget reactive-programming flutter state-management

假设 Flutter 应用使用 Redux 进行状态管理(flutter_redux)。

状态属于班级AppState,商店为Store<AppState>(例如:http://flutterbyexample.com/app-state-model)。

然后容器小部件使用依赖于StoreConnector<AppState, ...>的{​​{1}}。 这些小部件与AppState紧密耦合。那么我如何在其他应用中重用小部件,因为其他应用有不同的AppState

如果小部件依赖于AppState,并且AppState在这些小部件中很常见,我怎么能单独开发和测试容器小部件呢?

2 个答案:

答案 0 :(得分:2)

In this blog post我解释了如何开始在Flutter中使用Redux。

从代码示例中可以看出,您可以创建ViewModel类,而不是将WidgetState相关联,这意味着如果您创建ViewModel对于您计划重用的每个Widget的类,您应该能够创建测试ViewModel对象以进行测试,并在多个项目中重用这些Widget

编辑:

您可以创建一个特定于State的{​​{1}}类(即Widget,并使用ToggleState对象撰写您的应用State类:< / p>

ToggleState

并且您的class AppState { final ToggleWidgetState onOffState; } class ToggleWidgetState { final bool isOn; } 可以从ViewModel而不是整个ToggleWidgetState创建,因此请尝试从各种较小的状态对象中构建您的应用状态。

答案 1 :(得分:0)

我认为真正可重用的组件只是presentational个。

这些是其中没有状态管理(没有StoreConnector,没有StoreBuilder ...)的组件。

其他组件示例

class ExampleItem extends StatelessWidget {

  final Example example;

  ExampleItem({   
    @required this.example,
  });

  @override
  Widget build(BuildContext context) {
    return ListTile(        
        title: Hero(
          tag: '${example.id}__heroTag',
          child: Container(
            width: MediaQuery.of(context).size.width,
            child: Text(
              example.name,
              key: ExampleKeys.exampleItemName(example.id),
              style: Theme.of(context).textTheme.title,
            ),
          ),
        ),      
      );   
  }
}

容器组件示例

class ExampleContainer extends StatelessWidget {
  ExampleContainer({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return StoreConnector<AppState, _ViewModel>(     
      converter: _ViewModel.fromStore,
      builder: (context, vm) {
        return ExampleList(
          list: vm.list,        
        );
      },
    );
  }
}

class _ViewModel {
  final List<Example> list;

  _ViewModel({this.list});

  static _ViewModel fromStore(Store<AppState> store) {
    return _ViewModel(list: listSelector(store.state));
  }
}