如何为列表中的单个项目(而不是整个列表)编写 setter?
How do you write a setter for a single item in a list (not the whole list)?
我的模型中有一个 class,其中包含布尔列表。从我的 UI 我想通过 setter 在列表中的单个项目中设置 bool 状态(这样我也可以保存它)。我搞不懂语法(或者这是否有效)。
///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();
}
我知道我在这里遗漏了一些明显的东西,非常感谢任何帮助
get
和 set
函数不能接受任何参数。最简单的方法是使用普通函数:
bool getQuestionsAnswered(int index) => _questionsAnswered[index];
void setQuestionsAnswered(int index, bool value) {
_questionsAnswered[index] = value;
saveParameterBoolean(_questionAnsweredParamKeys[index], _questionsAnswered[index]);
updateState();
}
另一种选择是将 _questionsAnswered
从 List
更改为实现 operator []
(获取元素)和 operator []=
的自定义 class (设置一个元素),然后你可以让他们做任何你想做的事情。
我的模型中有一个 class,其中包含布尔列表。从我的 UI 我想通过 setter 在列表中的单个项目中设置 bool 状态(这样我也可以保存它)。我搞不懂语法(或者这是否有效)。
///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();
}
我知道我在这里遗漏了一些明显的东西,非常感谢任何帮助
get
和 set
函数不能接受任何参数。最简单的方法是使用普通函数:
bool getQuestionsAnswered(int index) => _questionsAnswered[index];
void setQuestionsAnswered(int index, bool value) {
_questionsAnswered[index] = value;
saveParameterBoolean(_questionAnsweredParamKeys[index], _questionsAnswered[index]);
updateState();
}
另一种选择是将 _questionsAnswered
从 List
更改为实现 operator []
(获取元素)和 operator []=
的自定义 class (设置一个元素),然后你可以让他们做任何你想做的事情。