Issue
I'm trying to remove a duplicate list element from my screen but cannot seem to do so. I have tried using .toSet().toList()
after having referred to previous solutions but that doesn't help as the duplicates keep on appearing. I would like to know how this can be achieved. This is my code:
class CartItems {
final String id;
final String name;
final String restaurantName;
final String price;
final int quantity;
final String image;
final String rating;
final String totalRatings;
CartItems(
{required this.id,
required this.name,
required this.restaurantName,
required this.price,
required this.quantity,
required this.image,
required this.rating,
required this.totalRatings});
}
class CartItemProvider with ChangeNotifier {
final List<CartItems> _cartItems = [];
List<CartItems> _individualItems = [];
List<CartItems> _restaurantTotal = [];
double deliveryCost = 40;
List<CartItems> get cartItems { //I access this getter using Providers in my widget class to display the items that are stored here
return [..._cartItems.toSet().toList()]; //Using the .toSet().toList() method which doesn't help
}
void addItems(String id, String name, String restaurantName, String price,
int quantity, String image, String rating, String totalRatings) {
_cartItems.add(CartItems(
id: id,
name: name,
restaurantName: restaurantName,
price: price,
quantity: quantity,
image: image,
rating: rating,
totalRatings: totalRatings));
notifyListeners();
}
void deleteItems(String id) {
_cartItems.removeWhere((element) => element.id == id);
notifyListeners();
}
// List<dynamic> getProductById(String id) {
// return _cartItems.where((element) => element.id == id).toList();
// }
List<CartItems> getProductById(String id) {
_individualItems = _cartItems.where((element) => element.id == id).toList();
return _individualItems;
}
double get itemTotal {
double total = 0.0;
return total;
}
double get totalAmount {
double total = 0.0;
_individualItems.forEach(
(value) => total += double.parse(value.price) * value.quantity);
return deliveryCost + total;
}
}
Here is a screenshot of the issue which shows duplicate elements:
Solution
The toSet().toList() won't work because you have different object references, they are not the same object reference - you need to compare the properties inside then. Why don't you, before adding them to the collection, check whether there's already an item with the same id; your updated addItems should look like:
void addItems(String id, String name, String restaurantName, String price,
int quantity, String image, String rating, String totalRatings) {
// if there's not an item with the same id, then add it
if (!_cartItems.any((c) => c.id == id) {
_cartItems.add(CartItems(
id: id,
name: name,
restaurantName: restaurantName,
price: price,
quantity: quantity,
image: image,
rating: rating,
totalRatings: totalRatings));
}
notifyListeners();
}
Answered By - Roman Jaquez
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.