我正在实施一个 redux 商店,我将商店视为不可变的。因此,商店看起来像这样:
class State {
final String firstname;
final String lastname;
State(this.firstname, this.lastname);
State.initial()
: this.firstname = null,
this.lastname = null;
State copy({String firstname, String lastname}) =>
new State(firstname ?? this.firstname, lastname ?? this.lastname);
}
Run Code Online (Sandbox Code Playgroud)
这一切正常,我可以复制状态并替换副本中的各个字段。
state.copy(firstname: "foo");
Run Code Online (Sandbox Code Playgroud)
但现在我当然不能将字段设置回 null。
state.copy(firstname: null);
Run Code Online (Sandbox Code Playgroud)
不起作用。
我也尝试过类似的事情:
State copy({String firstname = this.firstname, String lastname = this.lastname}) => ...
Run Code Online (Sandbox Code Playgroud)
但 Dart 不允许非 const 作为默认值。
您可以在文件中使用特殊标记,如下所示
const _noValueGiven = const Object();
class State {
...
State copy({String firstName: _noValueGiven, String lastName: _noValueGiven}) {
if (identical(firstName, _noValueGiven)) {
firstName = this.firstName;
}
...
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1113 次 |
| 最近记录: |