Dart| Flutter: How to initialize a final class variable in a constructor? | Flutter By Example

This tutorial explains how to initialize the final class variable in the constructor.

final variables are initialized only once, used only to initialize a variable at runtime. You can use static const for compile-time initialization values

Let’s declare the final class field, and initialize the field with the value in the constructor.

The below program gives Error: Final field ‘id’ is not initialized and Error: The setter ‘id’ isn’t defined for the class ‘Employee’.

class Employee {
  final int id;

  Employee() {
    this.id = 5;
  }
}

void main() {
  Employee emp = new Employee();
}

Then, How do you assign final variables in the constructor?

Dart provides a special syntax for the constructor.

How to initialize the final properties in Constructor?

Dart does not provide them to initialize the final variables in the constructor body.

You can initialize in constructor argument with new syntax as seen below

Syntax

Constructor(this.finalvariable)

The above code program can be rewritten with new syntax

class Employee {
  final int id;

  Employee(this.id) {}
}

void main() {
  Employee emp = new Employee(5);
}

Next, Let’s see how to add final private variables initialed in Constructor if you want to keep the final variable private, The below syntax is better

declare a variable as private with an underscore(_) for the variable name

class Employee {
  final int _id;

  Employee(int id) : _id = id;
}

void main() {
  Employee emp = new Employee(51);
}

Next, You can also add default parameter data for final fields using the {} syntax for providing a default value if the value is not passed.

Optional Final variable example initialization

class Employee {
  final int id;

  Employee({this.id = 0});
}

void main() {
  Employee emp = new Employee(5);
}

Finally, You can assign the final variables later at runtime using the late keyword

In this example, declare a final variable using late. Variable is assigned at runtime.

class Employee {
  late final int id;

  Employee(int j) {
    id = j * 2;
  }
}

void main() {
  Employee emp = new Employee(5);
}