I have this model:
Class Model {
Model({required this.title, required this.amount});
final String title;
final int amount;
}
User get to see this data and have an option to change the amount. When I try to change values of amount
like this list[index].amount = 3
I got "’amount’ can’t be used as a setter because it’s final. Try finding a different setter, or making ‘amount’ non-final" message. How can I update value of amount
?
Right now I’m using this workaround:
for (final model in list) {
if (model.title == _title) {
list[list.indexOf(model)] = Model(
title: model.title,
amount: _selectedAmount;
);
}
}
So, basically reassign it.
2
Answers
Final value can not be changed. remove the final keyword from the statement to make it changeable.
The final keyword is used to hardcode the values of the variable and it cannot be altered in future, neither any kind of operations performed on these variables can alter its value (state)
You can use
copyWith
method to create new instance with updated valueNow you can pass the filed you like to update like
model.copyWith(amount: _selectedAmount);