我正在尝试检查条件
if (value in List) {
exist
} else {
not exist
}
但是没有什么可以帮助任何有想法的人然后请分享。
My List = _quantityController[];
itemId 为整数
我想检查我的项目 ID 是否存在于我的列表数组中......谢谢!
list.contains(x);
以上是当前问题的正确答案。但是,如果像我这样的人来这里检查类对象列表中的值,那么这就是答案。
class DownloadedFile {
String Url;
String location;
}
下载文件列表
List<DownloadedFile> listOfDownloadedFile = List();
listOfDownloadedFile.add(...);
现在检查这个列表中是否有特定值
var contain = listOfDownloadedFile.where((element) => element.Url == "your URL link");
if (contain.isEmpty)
//value not exists
else
//value exists
也许有更好的方法/方法。如果有人知道,请告诉我。 :)
检查类对象数组
比 Abdullah Khan 更好的方法是使用 any 而不是 where 因为 where 使得数组被完全扫描。当它找到一个时,任何停止。
class DownloadedFile {
String Url;
String location;
}
List<DownloadedFile> files = [];
bool exists = files.any((file) => file.Url == "<some_url>");
这是我的情况 我有一个这样的列表 我在列表中寻找特定的 UUID
// UUID that I am looking for
String lookingForUUID = "111111-9084-4869-b9ac-b28f705ea53b"
// my list of comments
"comments": [
{
"uuid": "111111-9084-4869-b9ac-b28f705ea53b",
"comment": "comment"
},
{
"uuid": "222222-9084-4869-b9ac-b28f705ea53b",
"comment": "like"
}
]
这就是我在列表中迭代的方式
// This is how I iterate
var contain = someDataModel.comments.where((element) => element['uuid'] == lookingForUUID);
if (contain.isEmpty){
_isILike = false;
} else {
_isILike = true;
}
这样我就得到了 lookingForUUID
希望对某人有所帮助
如果您使用的是自定义类,请确保重写
==()
方法,以便 dart 可以比较两个对象。
使用它来检查数据是否在列表中:
mylist.contains(data)
这是一个完整的例子
void main() {
List<String> fruits = <String>['Apple', 'Banana', 'Mango'];
bool isPresent(String fruitName) {
return fruits.contains(fruitName);
}
print(isPresent('Apple')); // true
print(isPresent('Orange')); // false
}
indexOf
.
List<int> values = [2, 3, 4, 5, 6, 7];
print(values.indexOf(5) >= 0); // true, 5 is in values
print(values.indexOf(1) >= 0); // false, 1 is not in values
它还可以让您搜索索引。使用
contains
,一个人会做:
print(values.sublist(3).contains(6)); // true, 6 is after index 3 in values
print(values.sublist(3).contains(2)); // false, 2 is not after index 3 in values
与
indexOf
:
print(values.indexOf(6, 3) >= 0); // true, 6 is after index 3 in values
print(values.indexOf(2, 3) >= 0); // false, 2 is not after index 3 in values
检查 Map 中的特定元素是否包含特定值:
if (myMap.any((item) => item.myKeyName == whatever)) {
...
} else {
...
}
List<int> list1 = [1, 2, 2, 3];
List<int> list2 = [3, 2, 2, 1];
bool isEqual = list1.toSet().containsAll(list2) && list2.toSet().containsAll(list1);
print(isEqual);
这应该是真的。