如果对象不在array中,则添加到array中



我有一个包含我的body的数组,现在我想检查这个数组是否包含这个对象移除并添加新值,否则将其添加到我的body列表中。我怎样才能使这个条件生效?

这是我的身体:

createSwitchButtonBody(int index) {
body.add({
"value":
"product_attribute_${getBuilderResponseModel.data!.productAttributes![attributeValueIndex].id}",
"key": getBuilderResponseModel
.data!.productAttributes![attributeValueIndex].values![index].id,
});
print(body);
update();}

我想当make switchButton value = true时向数组中添加一个对象

试试下面的代码:

List myArray = [5, 7 , 10];
int bodyObject = 7;
int newObject = 12;
int i = 0;
bool isNotFoundYet = true;
while(i < (myArray.length-1) && isNotFoundYet){
if (myArray[i] == bodyObject) {
myArray.removeAt(i);
myArray.add(newObject);
isNotFoundYet = false;
}
else i++;}
if (isNotFoundYet) myArray.add(newObject);