如何使用 singleWhere 访问列表中的项目.. flutter

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

我正在使用

singleWhere
检查该项目是否已存在于 flutter 的列表中,但我无法在逻辑内访问该项目,这是我的代码:

if ((invoiceAdditionsList.singleWhere((it) => it.realID == invoiceAdditionInstance.realID,
   orElse: () => null)) !=
   null) {
      print('Already exists! $it');
      } else {
      print('not there');
        }


print('Already exists! $it');
行是错误,这里无法访问。

android ios flutter dart
1个回答
1
投票

您可以获取该项目,并根据结果将其存储。由于

singleWhere()
给出了单个现有项目,否则会抛出错误。做这样的事情,让我知道是否有效

var item = invoiceAdditionsList.singleWhere((it) => it.realID == invoiceAdditionInstance.realID, orElse: () => null); 

// and later check that element out
print("Element found $item" ?? "Not there")

如果您担心仅从列表中获取第一个找到的元素,则可以考虑使用 firstWhere(),因为

singleWhere()
在发现重复或未找到元素时会抛出错误。相同的代码,只是
firstWhere()

var item = invoiceAdditionsList.firstWhere((it) => it.realID == invoiceAdditionInstance.realID, orElse: () => null);

print("Element found: $item" ?? "Not there");

这只是给您的虚拟代码,为了更好地理解它,请使用

singleWhere()

void main() {
  List testIndex = [1,3,4,5,6,78,80];
  
  var item = testIndex.singleWhere((it) => it == 120, orElse: () => null); 
  print(item ?? "No item found"); // No item found
}
© www.soinside.com 2019 - 2024. All rights reserved.