Dart - 只允许设置类属性一次

问题描述

我想要一个只能设置一次的属性,然后忽略进一步设置它的尝试,因此没有人会意外设置或重置该值。

我知道 late 可以“有点”这样做,但是在使用 late 时,编译器和 IDE 都没有告诉我在调用 doOther() 之后调用 doOnce()会导致异常。

class Foo {
  bool? _bar;
  
  void doOnce() {
    if (_bar == null) {
      _bar = true;
      print('done this once');
    }
  }
  
  void doOther() {
    _bar = false; // this should not be possible when doOnce() is done
    print('done other');
  }
}

void main() {
  Foo foo = Foo();
  foo.doOnce();
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)