gpt4 book ai didi

dart - 遍历Dart中的类列表

转载 作者:行者123 更新时间:2023-12-03 04:23:26 25 4
gpt4 key购买 nike

class product {
String name;
String price;
String quantity;
product({this.name, this.price, this.quantity});
}

void main() {
List<product> listofProducts = [
product(name: "A", price: "10"),
product(name: "B", price: "10"),
product(name: "C", price: "10"),
product(name: "D", price: "10"),
product(name: "E", price: "10"),
product(name: "F", price: "10")
];
print(listofProducts.indexOf(product(name: "B", price: "10")));
}

如何在listofProducts列表中找到产品的索引(名称:“B”,价格:“10”)。

最佳答案

由于列表中的项目不是原始的,它们是引用类型,因此您需要在列表上使用indexWhere方法

final index = listofProducts.indexWhere((product) => product.name == "B" && product.price == "10");

print(index)

这样,您就可以遍历产品数组的每个元素并找到该产品的索引。因为您将引用类型作为项目。

关于dart - 遍历Dart中的类列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61207393/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com