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.
You can use copyWith
method to create new instance with updated value
class Model {
const Model({
required this.title,
required this.amount,
});
final String title;
final int amount;
Model copyWith({
String? title,
int? amount,
}) {
return Model(
title: title ?? this.title,
amount: amount ?? this.amount,
);
}
}
Now you can pass the filed you like to update like model.copyWith(amount: _selectedAmount);