How do I initialize a final class property in a constructor?

ConstructorDartFinal

Constructor Problem Overview


In Java you are allowed to do this:

class A {    
    private final int x;

    public A() {
        x = 5;
    }
}

In Dart, I tried:

class A {    
    final int x;

    A() {
        this.x = 5;
    }
}

I get two compilation errors:

> The final variable 'x' must be initialized.

and

> 'x' can't be used as a setter because its final.

Is there a way to set final properties in the constructor in Dart?

Constructor Solutions


Solution 1 - Constructor

You cannot instantiate final fields in the constructor body. There is a special syntax for that:

class Point {
  final num x;
  final num y;
  final num distanceFromOrigin;
  
  // Old syntax
  // Point(x, y) :
  //   x = x,
  //   y = y,
  //   distanceFromOrigin = sqrt(pow(x, 2) + pow(y, 2));

  // New syntax
  Point(this.x, this.y) :
    distanceFromOrigin = sqrt(pow(x, 2) + pow(y, 2));
}

Solution 2 - Constructor

You can make it even shorter with this. syntax in the constructor (described in https://www.dartlang.org/guides/language/language-tour#constructors):

class Point {
  final num x;
  final num y;
  final num distanceFromOrigin;

  Point(this.x, this.y)
      : distanceFromOrigin = sqrt(pow(x, 2) + pow(y, 2));
}

If you have some more complicated initialization you should use factory constructor, and the code become:

class Point {
  final num x;
  final num y;
  final num distanceFromOrigin;

  Point._(this.x, this.y, this.distanceFromOrigin);

  factory Point(num x, num y) {
    num distance = distanceFromOrigin = sqrt(pow(x, 2) + pow(y, 2));
    return new Point._(x, y, distance);
  }
}

Solution 3 - Constructor

Here is a simplified summary of the ways to initialize a final class variable.

class MyClass {
  final int x; //     <-- initialize this
}

Initializer value

class MyClass {
  final int x = 'hello'.length;
}

You'd only use final if the initialization could only be done at runtime. Otherwise, static const is better:

class MyClass {
  static const int x = 0;
}

Initializer formal

class MyClass {
  MyClass(this.x);
  final int x;
}

This is the most common approach.

Initializer list

class MyClass {
  MyClass(int x) 
    : _x = x;
  final int _x;
}

This is useful when you want to keep a field private.

Default parameter value

You can surround the parameter with square brackets ([]) for an unnamed parameter or curly braces ({}) for a named parameter and then give it a default value.

class MyClass {
  MyClass({this.x = 0});
  final int x;
}

This is useful if you want to make the parameter optional.

You could accomplish the same thing with an initializer list as well:

class MyClass {
  MyClass({int? x}) 
    : _x = x ?? 0;
  final int _x;
}

Late initialization

class MyClass {
  MyClass(String? a) {
    x = a?.length ?? 0;
  }
  late final int x;
}

This is useful if you need to do more complex initialization than is allowed in the initializer list. For example, I've done this when initializing a gesture recognizer in Flutter.

Lazy initialization

Another advantage of using late is that it doesn't initialize a value until you access the value.

class MyClass {
  late final int x = _doHeavyTask();
  int _doHeavyTask() {
    var sum = 0;
    for (var i = 0; i < 100000000; i++) {
      sum += 1;
    }
    return sum;
  }
}

This is useful if you have a heavy calculation that you only want call if you absolutely need it.

This doesn't initialize x:

final myClass = MyClass();

But this does initialize x:

final myClass = MyClass();
final value = myClass.x;

Solution 4 - Constructor

I've had a similar problem: I was trying to initialise a final field from the constructor, while simultaneously calling a super constructor. You could think of the following example

class Point2d {
  final int x;
  final int y;

  Point2d.fromCoordinates(Coordinates coordinates)
      : this.x = coordinates.x,
        this.y = coordinates.y;
}

class Point3d extends Point2d {
  final int z;

  Point3d.fromCoordinates(Coordinates coordinates)
      :this.z = coordinates.z,
        super.fromCoordinates(coordinates);
}
/// Demo class, to simulate constructing an object
/// from another object.
class Coordinates {
  final int x;
  final int y;
  final int z;
}

Well apparently this works. You can initialise your final fields by using the above syntax (check Point3d's constructor) and it works just fine!

Run a small program like this to check:

void main() {
  var coordinates = Coordinates(1, 2, 3);
  var point3d = Point3d.fromCoordinates(coordinates);
  print("x: ${point3d.x}, y: ${point3d.y}, z: ${point3d.z}");
}

It should prin x: 1, y: 2, z: 3

Solution 5 - Constructor

I've come to a dilemma here where I wanted to initialize a final List with no items, and a Stream to be defined inside the constructor (like in this case distanceFromOrigin).

I couldn't do that with any of the answers below, but I mixed them both and it worked.

Example:

class MyBloc {
  final BehaviorSubject<List<String>> itemsStream;
  final List<String> items = [];

  MyBloc() : this.itemsStream = BehaviorSubject<List<String>>.seeded([]) {
    items.addAll(List.generate(20, (index) => "Hola! I'm number $index"));
    itemsStream.add(items);
  }
}

Solution 6 - Constructor

class A{
  final int x;
  
  A(this.x){
  }
  
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBlackbamView Question on Stackoverflow
Solution 1 - Constructorw.brianView Answer on Stackoverflow
Solution 2 - ConstructorrkjView Answer on Stackoverflow
Solution 3 - ConstructorSuragchView Answer on Stackoverflow
Solution 4 - ConstructorSnuKiesView Answer on Stackoverflow
Solution 5 - ConstructorRafael Ruiz MuñozView Answer on Stackoverflow
Solution 6 - ConstructorAlexView Answer on Stackoverflow