'dart final property can change values [duplicate]
Hey guys I've searched the answers and didn't find it, so I'm asking.
I have a class with a list property, Dart Lint said to put the keyword 'final' before it. The final keyword should prevent the values to change, or I got it wrong?
class Questions {
final List<Question> _questionList = [
Question('Is the ocean blue', true),
Question('Is the sky blue', true),
];
//method that shouldn't work
void setQuestionAnswer(int questionNumber, bool newAns) {
_questionBank[questionNumber].questionAnswer = newAns;
}
}
//another file that have the class to the list above
class Question {
String questionText;
bool questionAnswer;
Question(this.questionText, this.questionAnswer);
}
Questions questionsk = Questions();
//this actually works, but a final property shouldn't be able to change
// values, why it works? I can change the value
questionsk.setQuestionAnswer(questionNumber, false);
Solution 1:[1]
The final keyword means you cannot assign a new value to __questionList.
For example, this code would give a compiler error:
_questionList = <Question>[];
You can however, do anything you want with the initial instance of the object. In case of a list you can change entries, add entries, remove entries or anything else.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | nvoigt |
