final keyword in Dart

What are final variables?

The final keyword is to declare a variable if you never intend to change the value.

The value of a final variable can be set only once.

There are multiple ways to declare final variable:

  1. final local variable.
  2. final instance variable.
  3. final library variable.

final local variable

The variable declaration within the functions are called local variable, add final keyword before the local variable to mark its as final.

The following code snippet shows how to declare the final local variable.

main() {
  // final local variable without type
  final name1 = 'Rock Star';

  // final local variable with explicitly type
  final String name2 = 'Rock Star';
}

final Instance variables

The variable declaration within the class are called instance variable, add final keyword before the instance variable to mark it as final.

Declare final instance variable:

The following code snippet shows how to declare final instance variable.

class Movie {
  final int id = 101;
  final String name = 'Iron man';
}

final instance variables must be initialized before the constructor body starts.

There are multiple ways to initialized final variable:

  1. Initialize at variable declaration
  2. Initialize by a constructor parameter
  3. Initialize in the constructor’s initializer list

Initialize at variable declaration

You can initialize final instance variable at variable declaration:

The following code snippet shows how to initialize final instance variable at declaration.

class Movie {
  final int id = 101;
  final String name = 'Iron man';
}

Initialize by a constructor parameter

You can also initialize Final instance variable by a constructor parameter:

The following code snippet shows how to initialize final instance variable by a constructor parameter and pass the values.

class Movie {
  final int id;

  final String name;

  // initialize final instance variable by a constructor parameter
  Movie(this.id, this.name);
}

main(List<String> args) {
  // Create an instance and pass final variable value
  var todo = Movie(101, 'Iron man');

  // print to console
  print('${todo.id} ${todo.name}'); // 101 Iron man
}

Initialize in the constructors initializer list

You can also initialize Final instance variable in the constructor’s initializer list:

The following code snippet shows how to initialize final instance variable in the constructor’s initializer list and pass the values.

class Movie {
  final int id;

  final String name;

  // Initialize Final instance variable in the constructor’s initializer list.
  Movie(id, name)
      : id = id,
        name = name {}
}

main(List<String> args) {
  // Create an instance and pass final variable value
  var todo = Movie(101, 'Iron man');

  // print to console
  print('${todo.id} ${todo.name}'); // 101 Iron man
}