0

说我有这样的代码

class MyClass {
  
  bool isLoading = false;
  String? errorMessage;
  
  void fetchData() {
    isLoading = true;
  }
  
}

正如您在fetchData方法中看到的那样,我设置isLoading为true。

我想要的是……

每当我设置isLoading为 true时,errorMessage属性将自动设置为 null。isLoading所以在我设置为 true后,我不必手动将 null 值分配给 errorMessage 属性

// 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
        }
    }
}
4

2 回答 2

0

你可以在 Dart 中使用 getter 和 setter 来拦截设置值。没有“didSet”拦截,你必须做一个完整的设置器并自己设置值。

class MyClass {
  // NOTICE: Don't set _isLoading directly, use [isLoading].
  bool _isLoading = false;
  String? errorMessage;
  
  void fetchData() {
    isLoading = true;
  }
  
  bool get isLoading => _isLoading;
  set isLoading(bool loading) {
    _isLoading = loading; 
    if (loading) errorMessage = null;
  }
}

不过,这不一定是我设计它的方式。对二传手的副作用是一种有点可疑的行为,可能会让一些人感到惊讶。

相反,它可能会有更精确的方法名称来启动和停止加载,这些方法看起来不像是无害的分配:

class MyClass {
  /// Whether we are currently loading.
  ///
  /// NOTICE: Do not set this variable directly, 
  /// use [startLoading] and [stopLoading] instead.
  bool _isLoading = false;
  
  String? errorMessage;
  
  void fetchData() {
    startLoading();
  }
  
  bool get isLoading => _isLoading;
  void startLoading() {
    _isLoading = true; 
    errorMessage = null;
  }
  void stopLoading() {
    _isLoading = false;
  }
}

这样,设置isLoading为 true 的唯一公开方法是调用startLoading. 您永远不应该直接分配给_isLoading. 如果您想控制他们何时被调用,您可以制作startLoading和私有化。stopLoading

于 2021-05-17T18:14:46.857 回答
0

如果你使用 Flutter,你可以看看ValueNotifier类。它允许您轻松添加/删除侦听器并触发对它们的更新。模仿 Observable 模式非常方便。此外(在 Flutter 的情况下),您甚至不需要依赖额外的包。

于 2022-01-18T18:42:08.173 回答