Junior — Middle
How can you ensure the immutability of a class object in your code?
sobes.tech AI
Answer from AI
To ensure immutability of a class object in Flutter (Dart), you can use the following approaches:
- Declare all class fields as
finalso they can only be initialized once. - Make the class
const-constructible if all fields are alsofinal. - Do not provide setters or methods that modify the object's state.
Example:
class User {
final String name;
final int age;
const User(this.name, this.age);
}
void main() {
const user = User('Ivan', 30);
// user.name = 'Peter'; // Error, final field
}
Thus, once an instance is created, its state cannot be changed, ensuring object immutability.