Oli*_*ult 2 redux flutter flutter-redux
我一直在使用 flutter_redux 几天,我想知道它们之间有什么区别:
class BtnCustom extends StatelessWidget {
@override
Widget build(BuildContext context) {
final store = StoreProvider.of<AppState>(context);
return FlatButton(
onPressed: store.dispatch(MyCustomAction),
child: Text(store.state.MyCustomTxt),
);
}
}
Run Code Online (Sandbox Code Playgroud)
和
class BtnCustom extends StatelessWidget {
@override
Widget build(BuildContext context) {
return StoreConnector<AppState, _ViewModel>(
converter: (store) => _ViewModel(
txt: store.state.MyCustomTxt,
onPressed: store.dispatch(MyCustomAction)),
builder: (BuildContext context, _ViewModel vm) {
return FlatButton(
onPressed: vm.onPressed,
child: Text(vm.txt),
);
},
);
}
}
class _ViewModel {
final String txt;
final void Function() onPressed;
_ViewModel({this.txt, this.onPressed});
}
Run Code Online (Sandbox Code Playgroud)
?
第一个看起来很方便使用。我应该注意使用一种而不是另一种的优点或缺点吗?
根据文档,StoreConnector 将在其中重建小部件,以便:
StoreConnector使您可以更好地控制小部件,尤其是当您不想重建它时。StoreConnector:
您可以检测是否ViewModel发生了变化(Widget是否应该重建)如果你使用distinct: true和覆盖hashCode,并==在你的ViewModel;
通过快速检查一些特定的内容,您可以完全跳过小部件重建store.state:
StoreConnector<AppState, MyViewModel>(
distinct: true,
ignoreChange: (state) {
return state.someVariable == theValueIDontCareAbout;
},
...
),
class MyViewModel{
@override
bool operator ==(other) {
return (other is MyViewModel) && (this.someVmVariable == other.someVmVariable);
}
@override
int get hashCode {
int result = 17;
result = 37 * result + someVmVariable.hashCode;
return result;
}
}
Run Code Online (Sandbox Code Playgroud)
还有一些更细粒度的控件。查看StoreConnector的构造函数的文档。如果 store sonnector 中的多个小部件共享同一个 ViewModel,那么它们很自然。但是,如果可以通过分离它们的ViewModels来防止它们重新构建,那么您可以使用单独的StoreConnectors。
| 归档时间: |
|
| 查看次数: |
1681 次 |
| 最近记录: |