I have a simple question, I have dummy data about some products and I need to take all categories into the new list. How can I do it?
class Products with ChangeNotifier {
List<Product> _productItems = [
Product(
id: 'p1',
title: 'Red Shirt',
price: 29.99,
category: 'shirts',
),
Product(
id: 'p2',
title: 'Trousers',
description: 'A nice pair of trousers.',
price: 59.99,
category: 'Trousers',
),
Product(
id: 'p3',
title: 'Yellow Scarf',
price: 19.99,
category: 'Scarfs',
),
Product(
id: 'p4',
title: 'A Pan',
price: 49.99,
category: 'Pans',),];
List<Product> get items {
return [...items];
}
List<Product> get fovoriteItems {
return _productItems.where((prodItem) => prodItem.isFavorite!).toList();
}
List<Product> get stockItems {
return _productItems.where((prodItems) => prodItems.isStock!).toList();
}
List<Product> get categoriesList {}
}
I need to take a List
like categories = [Shirts,Trousers,Scarfs,Pans];
CodePudding user response:
Your problem isn't clear but there are notable issues in your code. You firstly need to update your items
method to return all the products. So update it to something like this:
List<Product> get items {
return _productItems;
}
Then in the get favoriteItems
method, you have not defined the isFavorite
property in any of the dummy classes. So update them to include it. This also goes for your get stockItems
method. Here's an example:
Product(
id: 'p9',
title: 'Apples',
description: 'A delicious red treat',
price: 1.99,
category: 'Food',
isFavorite: false,
isStock: true,
),
Also make sure to remove the !
from prodItem.isFavorite! and prodItems.isStock! because this will give the opposite result.
The categoriesList
method should be of type String
because a category isn't necessarily product. Here's the implementation:
List<String> get categories {
List<String> ctgrs = [];
for (item in _productItems) {
ctgrs.add(item.category);
}
return ctgrs;
}
I would also highly recommend using UniqueKey()
or using the UUID package for every product's id
so you don't have to make a custom one for every product. Using UUID is very secure as well.
CodePudding user response:
List<String> categories = [];
_productItems.forEach((element) {
if (categories.indexOf(element.category) < 0) {//avoid duplicates
categories.add(element.category);
}
});