Initialize a final variable with “this” in Dart

╄→尐↘猪︶ㄣ 提交于 2019-12-24 19:44:17

问题


I have a class like this:

class A extends B {
  final Property<bool> property = Property<bool>(this);
}

class Property<T> {
  Property(this.b);
  final B b;
}

But I get an error on this saying:

Invalid reference to 'this' expression.

I believe I can't access this at that moment, probably because the object reference is not ready yet.

So I tried other forms of initializing that variable like:

class A extends B {
  final Property<bool> property;
  A() : property = Property<bool>(this);
}

But I get the same error.

The only thing that works is:

class A extends B {
  Property<bool> property;
  A() {
   property = Property<bool>(this);
  }
}

Which needs me to remove the final variable declaration, which is something I don't want to.

How can I initialize a final variable in Dart that needs a reference to the object itself?


回答1:


You can't reference this in any initializers as this hasn't yet been initialized itself, so you won't be able to set Property<bool> property to be final.

If you're just trying to prevent modification of the value of property from outside the instance, you can use a private member and provide a getter to prevent modification. Given your example, that would look something like this:

class A extends B {

  // Since there's no property setter, we've effectively disallowed
  // outside modification of property.
  Property<bool> get property => _property;
  Property<bool> _property;

  A() {
   property = Property<bool>(this);
  }
}


来源:https://stackoverflow.com/questions/59449666/initialize-a-final-variable-with-this-in-dart

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!