我打算在 Flutter 检测到列表中有重复项时退出我的 if else 或循环语句。但是当我把
break
放在 if 和 else 语句中时,它并不能很好地工作。当我把 break
放在 if 中时,即使 if 语句有 break
循环,else 语句也会继续执行。如果我把 break
放在 else 语句中,那么 if 语句根本不会执行,因为 else 语句中的 break
会影响 i++
。而如果我在 if 和 else 语句中都放入 break
,它表明我的 i++
是死代码。
代码如下:
void addFavourite() {
favouriteCountry.add(properties[0]['name']);
}
void checkDuplicates() {
int length = favouriteCountry.length;
String cName = properties[0]['name'];
if (length > 0) {
for (int i = 0; i < length; i++) {
String name = favouriteCountry[i];
print(name);
if (name == cName) {
print(length);
showDialog<void>(
context: context,
barrierDismissible: false, // user must tap button!
builder: (BuildContext context) {
return AlertDialog(
title: const Text(
'Duplicated action, country already added to list.'),
content: SingleChildScrollView(
child: ListBody(
children: const <Widget>[
Text('You really liked this country huh?'),
],
),
),
actions: <Widget>[
TextButton(
child: const Text('OK'),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
},
);
break;
} else {
addFavourite();
displayAddFavourite();
print("object");
}
}
} else {
addFavourite();
displayAddFavourite();
print("object1");
}
}
我试着把 i++ 放在 if 和 else 语句中,但它不起作用。因此,如果有什么我可以添加到我的代码中以使其工作。请不吝赐教。提前致谢!
您可以考虑使用
flag
并相应地显示 dialog
。
void checkDuplicates() {
int length = favouriteCountry.length;
String cName = properties[0]['name'];
bool foundDuplicate = false; // set this flag
for (int i = 0; i < length; i++) {
String name = favouriteCountry[i];
print(name);
if (name == cName) {
foundDuplicate = true;
break;
}
}
if (foundDuplicate) {
showDialog<void>(
context: context,
barrierDismissible: false,
builder: (BuildContext context) {
// ...
},
);
} else {
addFavourite();
displayAddFavourite();
print("object");
}
}