How do I initialize a final field in constructor's body?

It's not possible to assign a final field in a constructor body. The final field needs to be assigned before the constructor body, in the initializer list or on declaration:

class ClassName
{
    final OtherClass field = new OtherClass(); // Here

    ClassName()
        : field = new OtherClass() // or here 
    {
     
    }
}

As you can't use this in the initializer list or on the declaration, you can't do what you plan to do.


There are 3 ways to initialise a final field in a class.

  • Initialise it in constructor parameter.

    class Foo {
      final int bar;
    
      // Initialising in constructor parameter.
      Foo(this.bar);
    }
    
  • Use initialiser list.

    class Foo {
      final int bar;
    
      // Initialiser list
      Foo() : bar = 1;
    }    
    
  • Combination of both.

    class Foo {
      final int bar;
    
      Foo(int value) : bar = value;
    }
    

Tags:

Dart