Dart中是否有类似于财产观察者的东西?
假设我有这样的代码Dart中是否有类似于财产观察者的东西?,dart,Dart,假设我有这样的代码 class MyClass { bool isLoading = false; String? errorMessage; void fetchData() { isLoading = true; } } 正如您在fetchData方法中看到的,我将isLoading设置为true 我想要的是 每当我将isLoading设置为true时,errorMessage属性将自动设置为null。因此,在我将isLoading设置为true之
class MyClass {
bool isLoading = false;
String? errorMessage;
void fetchData() {
isLoading = true;
}
}
正如您在fetchData
方法中看到的,我将isLoading
设置为true
我想要的是
每当我将isLoading
设置为true时,errorMessage
属性将自动设置为null。因此,在我将isLoading
设置为true之后,我不必手动为errorMessage属性分配null值
// in a method
isLoading = true
errorMessage = null
// in another method
isLoading = true
errorMessage = null
// it is cumbersome to reassign error to be null over and over again after set isLoading to be true
isLoading = true
errorMessage = null
在Swift中,我可以使用一种叫做属性观察器的东西来完成它
var errorMessage : String?
var isLoading: bool {
didSet {
if (isLoading == true) {
errorMessage = null
}
}
}
您可以在Dart中使用getter和setter截取设置值。没有“didSet”截取,你必须做一个完整的setter并自己实际设置值
class-MyClass{
//注意:不要直接设置_isLoading,请使用[isLoading]。
bool_isLoading=false;
字符串?错误消息;
void fetchData(){
isLoading=true;
}
bool get isLoading=>\u isLoading;
设置isLoading(布尔加载){
_卸载=加载;
如果(加载)errorMessage=null;
}
}
不过,这不一定是我设计它的方式。
二传手的副作用是一种稍有可疑的行为,可能会让一些人感到惊讶
它可能会有更精确的方法名来启动和停止加载,这些方法名看起来不像无害的赋值:
class-MyClass{
///我们当前是否正在加载。
///
///注意:不要直接设置此变量,
///改用[startLoading]和[stopLoading]。
bool_isLoading=false;
字符串?错误消息;
void fetchData(){
惊人的负荷();
}
bool get isLoading=>\u isLoading;
虚空惊人{
_isLoading=true;
errorMessage=null;
}
无效停止加载(){
_isLoading=false;
}
}
这样,将isLoading
设置为true的唯一公开方法是调用startLoading
。
您不应该直接分配给\u isLoading
。
如果您想控制调用它们的时间,可以将startLoading
和stopLoading
设置为private