Search code examples
dartfinal

Initialize a final variable with "this" in Dart


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?


Solution

  • 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);
      }
    }