Как извлечь продукт из списка продуктов для определенного идентификатора продукта?

#dart

#dart

Вопрос:

пожалуйста, помогите мне!

     List<String> Id= ["MES9-7t73JhFzAEoL6J","MES91YJevIAthak253M"];

    List<Product> products =
          [
            Product(
              id: 'MES9-2',
              categories: 'AC1, AC2, AC3, N1, Pn1, P',
              title: 'Red Shirt',
              description: 'A red shirt - it is pretty red!',
              price: 29.99,
              imageUrl:
                'https://cdn.pixabay.com/photo/2016/10/02/22/17/red-tshirt-1710578_1280.jpg',
              ),
           Product(
             categories:' pn2, N2, N3, Pn2, Pn3',
             id: 'MES91YJevIAthak253M',
             title: 'Trousers',
             description: 'A nice pair of trousers.',
             price: 59.99,
             imageUrl:
              'https://upload.wikimedia.org/wikipedia/commons/thumb/e/e8/Trousers,_dress_(AM_1960.022-8).jpg/512px-Trousers,_dress_(AM_1960.022-8).jpg',
             ),
           ];
  

=> Как извлечь продукт из списка _items, где идентификатор продукта совпадает со строкой в списке идентификаторов.

Ответ №1:

Попробуйте это:

 final product = products.firstWhere((p) => Id.contains(p.id));
  

Ответ №2:

Вам нужно запустить два цикла for, чтобы извлечь список продуктов, соответствующий списку идентификаторов продуктов, которые у вас есть. Первый цикл будет выполняться в соответствии с длиной полученных вами идентификаторов, а второй — в соответствии с длиной продуктов. Он сопоставит оба идентификатора в условии if и добавит соответствующие продукты в foundProducts список.

 findProducts(){
    List<Product> foundProducts = [];
    for(int i=0; i<listOfIds.length;  i){
      for(int j=0;  j<productList.length;   j){
        if(listOfIds[i] == productList[j].id){
          foundProducts.add(productList[j]);
        }
      }
    }
  }
  

Ответ №3:

Вам просто нужно выполнить итерацию по вашему списку, найти совпадение и вернуть его. Вы можете сделать это через firsWhere().

Итак, вам придется выполнить итерацию по вашему, Id используя list iterate dart

 //you have the List<Product> we are taking the variable as products
List<Product> products = ....

// this will store the item which matches the id
var item;
Id.forEach((id){
  //now using first where
  products.firstWhere((item) => item.id == id, orElse: () => null);
});

// now printing the item and check for the nullability
print(item ?? 'No products found'); // You will get the matching the Product matching the item id
  

Пожалуйста, обратите внимание: firstWhere() выдает первый элемент, найденный в списке, соответствующий любому из идентификаторов. Таким образом, вы будете использовать только один продукт. Я предполагаю только для одного требования.

У меня есть демо для вас. Здесь вы можете увидеть, как это работает

ДЕМОНСТРАЦИЯ

 class Product {
  double price;
  String id, categories, title, description, imageUrl;
  
  Product({
    this.id, 
    this.categories, 
    this.title, 
    this.description, 
    this.price, 
    this.imageUrl
  });
}

void main() {
  var resu<
  List<String> id = ["MES9-7t73JhFzAEoL6J","MES91YJevIAthak253M"];
  List<Product> products = [
    Product(
      id: 'MES9-2',
      categories: 'AC1, AC2, AC3, N1, Pn1, P',
      title: 'Red Shirt',
      description: 'A red shirt - it is pretty red!',
      price: 29.99,
      imageUrl:
          'https://cdn.pixabay.com/photo/2016/10/02/22/17/red-t-shirt-1710578_1280.jpg',
    ),
    Product(
      categories:' pn2, N2, N3, Pn2, Pn3',
      id: 'MES91YJevIAthak253M',
      title: 'Trousers',
      description: 'A nice pair of trousers.',
      price: 59.99,
      imageUrl:
          'https://upload.wikimedia.org/wikipedia/commons/thumb/e/e8/Trousers,_dress_(AM_1960.022-8).jpg/512px-Trousers,_dress_(AM_1960.022-8).jpg',
    )
  ];
  
  // Here is what we're doing the main operation
  id.forEach((id){
    result = products.firstWhere((item) => item.id == id, orElse: () => null);
  });
  
  //printing the result
  print(result ?? "No items found");
  // similary you can get the result item via result.id
  print("RESULT: ${result.id}, ${result.categories}, ${result.title}");
}
  

Вывод

 Instance of 'Product' // so this is the instance of the product
RESULT: MES91YJevIAthak253M,  pn2, N2, N3, Pn2, Pn3, Trousers