flutter:obs的call方法

  1. 普通类的Call方法–Callable 类
  2. Rx<T> 的 call 方法

普通类的Call方法–Callable 类

在 Dart 里,如果一个类实现了 call() 方法,那么它的实例可以像函数一样被调用,这种类叫 callable class可调用类)。

class Adder {
  int call(int a, int b) => a + b;
}

void main() {
  var add = Adder();
  
  print(add(3, 4)); // 7,像函数一样调用
}

特点

  • call() 方法可以有任意参数和返回值
  • 调用时不需要写 add.call(3, 4),直接 add(3, 4) 就行

Rx<T>call 方法

Rx<T> 里面定义了一个call 方法

T call([T? v]) {
  if (v != null) {
    value = v;
  }
  return value;
}

在使用的时候可以这样:

// UserProfileModel 是自定义的类
// _profile 的类型是 Rx<UserProfileModel>
final _profile = UserProfileModel().obs;

_profile(UserProfileModel());

// 上面那句代码完全等价于:
_profile.value = UserProfileModel();

×

喜欢就点赞,疼爱就打赏