[英]Flutter: How to update final int value in model?
我有這個 model:
Class Model {
Model({required this.title, required this.amount});
final String title;
final int amount;
}
用戶可以看到這些數據並可以選擇更改數量。 當我嘗試像這個list[index].amount = 3
那樣更改amount
的值時,我得到“‘ amount’不能用作 setter,因為它是最終的。嘗試尋找不同的 setter,或者使‘amount’成為非最終的“ 信息。 如何更新amount
的值?
現在我正在使用這個解決方法:
for (final model in list) {
if (model.title == _title) {
list[list.indexOf(model)] = Model(
title: model.title,
amount: _selectedAmount;
);
}
}
所以,基本上重新分配它。
最終值無法更改。 從語句中刪除 final 關鍵字以使其可變。 final 關鍵字用於對變量的值進行硬編碼,以后不能更改,對這些變量執行的任何類型的操作都不能更改其值(狀態)
您可以使用copyWith
方法創建具有更新值的新實例
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,
);
}
}
現在您可以傳遞您想要更新的文件,例如model.copyWith(amount: _selectedAmount);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.