使用Set关键字时出现Flutter Dart Setter问题

问题描述

被介绍给BLoC时,我创建了一个简单的类来更改bool变量的值:

class SignInBloc {
  
  StreamController<bool> _isLoading = StreamController<bool>();

  Stream<bool> get getIsLoading => _isLoading.stream;
  set setIsLoading(bool isLoading) => _isLoading.sink.add(isLoading); // Here is my problem (set)

  void dispose(){
    _isLoading.close();
  }
}

当我使用set关键字,然后在我的UI屏幕中调用它时:bloc.setIsLoading(false); 我有一个例外:

Try correcting the name to the name of an existing method,or defining a method named 'setIsLoading'.

但是当我在set类中取消SignInBloc关键字时,它可以正常工作。我很困惑,不是最好使用此关键字而不是直接声明我的二传手吗?和, 为什么我在起飞时没有收到错误消息?

解决方法

设置器的使用要像它们是该类的公共领域一样。您只是在明确定义自己的setter。像这样直接将您的预期值分配给设置器:

bloc.setIsLoading = false;

使用set的唯一好处是能够使用此语法。

起飞set时,它已更改为常规方法,其中bloc.setIsLoading(false);是正确的语法。