'final variables can't be reassigned, but the object can be mutated in flutter

https://stackoverflow.com/a/55990137/462608
comment:

"Can't be changed after initialized" is ambiguous. final variables can't be reassigned, but the object can be mutated. – jamesdlin Feb 19 at 17:43

and https://stackoverflow.com/a/50431087/462608

a final variable's value cannot be changed. final modifies variables

What do both these statements mean? Please give examples.



Solution 1:[1]

Imagine the example below:

void main() {
  final student = Student('Salih', 29);
  print('Student before $student');
  student.age = 30;
  print('Student after $student');
}


class Student {
  Student(this.name, this.age);
  
  final String name;
  int age;
  
  @override
  String toString() => 'Age is $age and name is $name';
}

One of the fields of the Student object is mutable. This way we can reassign it. What others mean above is that, the object reference of the final variables will be assigned first but internals of the object can be changed.

In our example, final would be preventing to re-assign something to student object but it will not prevent us to re-assign a value within the object.

You can run the code on dartpad.dev above and see the result as follows:

Student before Age is 29 and name is Salih
Student after Age is 30 and name is Salih

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 salihgueler