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:
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';
}
The variable declaration within the class are called instance variable, add final
keyword before the instance variable to mark it as final.
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:
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';
}
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
}
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
}