检查数组中的值是否存在 Flutter dart

问题描述 投票:0回答:10

我正在尝试检查条件

if (value in List) {
  exist
} else { 
  not exist
}

但是没有什么可以帮助任何有想法的人然后请分享。

My List = _quantityController[];

itemId 为整数

我想检查我的项目 ID 是否存在于我的列表数组中......谢谢!

dart flutter
10个回答
243
投票
list.contains(x);

包含方法


44
投票

以上是当前问题的正确答案。但是,如果像我这样的人来这里检查类对象列表中的值,那么这就是答案。

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

也许有更好的方法/方法。如果有人知道,请告诉我。 :)


22
投票
List<int> values = [1, 2, 3, 4];
values.contains(1); // true
values.contains(99); // false   

Method - Contains of Iterable 完全满足您的需求。见上面的例子。


21
投票

检查类对象数组

比 Abdullah Khan 更好的方法是使用 any 而不是 where 因为 where 使得数组被完全扫描。当它找到一个时,任何停止。

class DownloadedFile {
 String Url;
 String location;
}

List<DownloadedFile> files = [];
bool exists = files.any((file) => file.Url == "<some_url>");

7
投票

这是我的情况 我有一个这样的列表 我在列表中寻找特定的 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

希望对某人有所帮助


6
投票

如果您使用的是自定义类,请确保重写

==()
方法,以便 dart 可以比较两个对象。

使用它来检查数据是否在列表中:

mylist.contains(data)

5
投票

这是一个完整的例子

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
}

1
投票

其他答案没有提到的解决方案:

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

1
投票

检查 Map 中的特定元素是否包含特定值:

if (myMap.any((item) => item.myKeyName == whatever)) {
  ...
} else {
  ...
}

0
投票
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);

这应该是真的。

© www.soinside.com 2019 - 2024. All rights reserved.