skip to Main Content

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


  1. 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)

    Login or Signup to reply.
  2. 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);

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search