How do you write a setter for a single item in a list (not the whole list)?
207
get
and set
functions can't take any arguments. The simplest approach would be to use normal functions:
bool getQuestionsAnswered(int index) => _questionsAnswered[index];
void setQuestionsAnswered(int index, bool value) {
_questionsAnswered[index] = value;
saveParameterBoolean(_questionAnsweredParamKeys[index], _questionsAnswered[index]);
updateState();
}
Another alternative would be to change _questionsAnswered
from a List
to a custom class that implements operator []
(to get an element) and operator []=
(to set an element), and then you could make them do whatever you want.
Author by
Chris Bennett
Updated on December 01, 2022Comments
-
Chris Bennett over 1 year
I have a class in my model that includes a list of bool. From my UI I want to set the bool state in just a single item in the list via a setter (so that I can also save it). I can't figure out the syntax (or whether this is a valid thing to do).
///This is OK set notificationDismissed(bool notificationDismissed){ _notificationDismissed = notificationDismissed; saveParameterBoolean(_notificationDismissedKey, _notificationDismissed); } bool get notificationDismissed => _notificationDismissed; ///This is OK too List<bool> get questionsAnswered => _questionsAnswered; set questionsAnswered(List<bool> questionsAnswered){ _questionsAnswered = questionsAnswered; for(int i=0; i<_questionAnsweredParamKeys.length; i++ ){ saveParameterBoolean(_questionAnsweredParamKeys[i], _questionsAnswered[i]); } updateState(); } ///This is not OK !!!! but should show what I want to do List<bool> get questionsAnswered[index] => _questionsAnswered[index]; set questionsAnswered[index](bool questionsAnswered[index]){ _questionsAnswered[index] = questionsAnswered[index]; saveParameterBoolean(_questionAnsweredParamKeys[index], _questionsAnswered[index]); updateState(); }
I know I'm missing something obvious here, any help greatly appreciated
-
Chris Bennett about 5 yearsAwesome, thank you, I'll just implement a function and move on :-)
-
Kasandrop about 3 yearsThat is not true! set functions take arguments in dart but only one