The final keyword in Dart, which is also used in Flutter (since Flutter is built using Dart), is used to create a variable that can be set only once. This means that the value of a final variable can be assigned at runtime, but once it is assigned, it cannot be changed.
final helps in creating immutable state which is beneficial for performance and avoiding bugs related to state changes.final variables are often used with required parameters in constructors to ensure they are set during object creation.final is used for variables that are assigned once and do not change thereafter.final variables are initialized at runtime, unlike const which must be initialized at compile time.void main() { // Final variable example final name = 'Alice'; // 'name' is initialized only once // name = 'Bob'; // This will cause an error
final int age; age = 30; // 'age' is assigned only once // age = 31; // This will cause an error
print(name); // Output: Alice print(age); // Output: 30 }
When final is used with objects, the reference to the object is final, but the properties of the object can still be modified if they are not declared as final.
class Person { String name; Person(this.name); }
void main() { final person = Person('Alice'); person.name = 'Bob'; // Allowed: modifying a property // person = Person('Charlie'); // Not allowed: reassigning the final variable
print(person.name); // Output: Bob }